Android Printing using custom Print service - android

I am trying to write a custom android print service. I have followed the instruction mentioned in the below blog:
https://github.com/zaki50/MyPrintServiceProject
I am able to create a service, which executes a print job. But after the job doesn't print any thing. My question is, what is the localId that we should provide. Is it printer ip, name? Also is there any way to know why the print job doesn't work.
Basically the two methods that I am concerned about are adding onStartPrinterDiscovery and OnPrintJobQueue as mentioned below:
#Override
public void onStartPrinterDiscovery(List<PrinterId> priorityList) {
String str = Settings.Secure.getString(getBaseContext().getContentResolver(), "enabled_print_services");
Log.d("myprinter", "PrinterDiscoverySession#onStartPrinterDiscovery(priorityList: " + priorityList + ") called")
final List<PrinterInfo> printers = new ArrayList<>();
final PrinterId printerId = generatePrinterId("D8:49:2F:64:04:DB");
final PrinterInfo.Builder builder = new PrinterInfo.Builder(printerId, "D8:49:2F:64:04:DB", PrinterInfo.STATUS_IDLE);
PrinterCapabilitiesInfo.Builder capBuilder = new PrinterCapabilitiesInfo.Builder(printerId);
capBuilder.addMediaSize(PrintAttributes.MediaSize.NA_LETTER, true);
capBuilder.addMediaSize(PrintAttributes.MediaSize.NA_LETTER, false);
capBuilder.addResolution(new PrintAttributes.Resolution("resolutionId", "default resolution", 600, 600), true);
capBuilder.setColorModes(PrintAttributes.COLOR_MODE_COLOR | PrintAttributes.COLOR_MODE_MONOCHROME, PrintAttributes.COLOR_MODE_COLOR);
builder.setCapabilities(capBuilder.build());
printers.add(builder.build());
addPrinters(printers);
}
#Override
protected void onPrintJobQueued(PrintJob printJob) {
Log.d("myprinter", "queued: " + printJob.getId().toString());
printJob.start();
//printJob.complete();
final PrintDocument document = printJob.getDocument();
final FileInputStream in = new FileInputStream(document.getData().getFileDescriptor());
try {
final byte[] buffer = new byte[4];
#SuppressWarnings("unused")
final int read = in.read(buffer);
Log.d("myprinter", "first " + buffer.length + "bytes of content: " + toString(buffer));
} catch (IOException e) {
Log.d("myprinter", "", e);
} finally {
try {
in.close();
} catch (IOException e) {
assert true;
}
}
if( printJob.isStarted()){
printJob.complete();
}
}
My Question is what should be printerId(or localId). How do we know if the printjob has succeeded or failed

You can do detection of print job status with other methods in the class:
if( printJob.isStarted() ){
}
else if( printJob.isCompleted() ){
}
else if( printJob.isCancelled() ){
}
else if( printJob.isFailed() ){
}
In addition, the print service has it's own methods listed in the docs:
#Override
protected void onPrintJobQueued(PrintJob printJob) {
Log.d("printer", "queued: " + printJob.getId().toString());
printJob.start();
//...
printJob.complete();
}
#Override
protected void onRequestCancelPrintJob(PrintJob printJob) {
Log.d("printer", "canceled: " + printJob.getId().toString());
printJob.cancel();
}

Related

OpenCV face recognition with Android

I am very new to android, as I got a project for maintenance. I completed other part of the project like authentication, token setting etc... In that face recognition is used to identify the person. Previously it was working fine and taken images, trained with it and recognized the person.(Obviously not done by me :)). Now it throws error as
Add Person ActivityCvException [org.opencv.core.CvException:
cv::Exception:
/build/master_pack-android/opencv/modules/core/src/matrix.cpp:1047:
error: (-13) The matrix is not continuous, thus its number of rows can
not be changed in function cv::Mat cv::Mat::reshape(int, int) const
Code sample is as follows
public void training() {
Thread thread;
try{
PreferenceManager.setDefaultValues(getApplicationContext(), R.xml.preferences, false);
}catch (Exception e){
AddPersonActivity.this.runOnUiThread(new Runnable() {
public void run() {
WriteLog("Add Person Activity" +e.fillInStackTrace());
errorAlert("Add Person Activity" +e.fillInStackTrace());
VolleyHelper.progressDialog.dismiss();
}
});
}
WriteLog("training 1 ");
final Handler handler = new Handler(Looper.getMainLooper());
thread = new Thread(new Runnable() {
public void run() {
if (!Thread.currentThread().isInterrupted()) {
try {
WriteLog("training 2 ");
PreProcessorFactory ppF = new PreProcessorFactory(AddPersonActivity.this);
PreferencesHelper preferencesHelper = new PreferencesHelper(AddPersonActivity.this);
String algorithm = preferencesHelper.getClassificationMethod();
FileHelper fileHelper = new FileHelper();
fileHelper.createDataFolderIfNotExsiting();
final File[] persons = fileHelper.getTrainingList();
if (persons.length > 0) {
Recognition rec = RecognitionFactory.getRecognitionAlgorithm(getApplicationContext(), Recognition.TRAINING, algorithm);
for (File person : persons) {
if (person.isDirectory()) {
File[] files = person.listFiles();
int counter = 1;
for (File file : files) {
if (FileHelper.isFileAnImage(file)) {
Mat imgRgb = Imgcodecs.imread(file.getAbsolutePath());
Imgproc.cvtColor(imgRgb, imgRgb, Imgproc.COLOR_BGRA2RGBA);
Mat processedImage = new Mat();
imgRgb.copyTo(processedImage);
List<Mat> images = ppF.getProcessedImage(processedImage, PreProcessorFactory.PreprocessingMode.RECOGNITION);
if (images == null || images.size() > 1) {
continue;
} else {
processedImage = images.get(0);
}
if (processedImage.empty()) {
continue;
}
String[] tokens = file.getParent().split("/");
final String name = tokens[tokens.length - 1];
for (int i = 0; i < files.length; i++) {
File myfile = new File(person +
"\\" + files[i].getName());
String long_file_name = files[i].getName();
System.out.println(long_file_name);
System.out.print(long_file_name);
myfile.renameTo(new File(person +
"\\" + long_file_name + "_101" + ".png"));
}
WriteLog("training 3 ");
MatName m = new MatName("processedImage", processedImage);
fileHelper.saveMatToImage(m, FileHelper.DATA_PATH);
rec.addImage(processedImage, name, false);
counter++;
}
}
}
}
try {
if (rec.train()) {
if (zipFileAtPath("/storage/emulated/0/Pictures/facerecognition/training/" + lcode, "/storage/emulated/0/Pictures/facerecognition/data/SVM/" + lcode + ".zip")) {
WriteLog("training 4 ");
if (zipFileAtPath("/storage/emulated/0/Pictures/facerecognition/data/SVM", "/storage/emulated/0/Pictures/facerecognition/" + "SVM_" + lcode + ".zip")) {
WriteLog("training 5 ");
fileupload(getintent.getStringExtra("lcode"));
} else {
Toast.makeText(getApplicationContext(), "No Face Recognised", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "No Face Recognised", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Try Again", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
WriteLog("Add Person Activity" +e.fillInStackTrace());
errorAlert("Add Person Activity" +e.fillInStackTrace());
}
handler.post(new Runnable() {
#Override
public void run() {
}
});
} else {
Thread.currentThread().interrupt();
}
} catch (Exception e) {
AddPersonActivity.this.runOnUiThread(new Runnable() {
public void run() {
VolleyHelper.progressDialog.dismiss();
WriteLog("Add Person Activity" +e.fillInStackTrace());
errorAlert("Add Person Activity" +e.fillInStackTrace());
}
});
}
}
}
});
thread.start();
}
The input image needs to be stored as a continuous block of bytes in memory. I came to a similar situation, particularly because Android (at least the version I tried) does not seem to store images continuously. 1) Check if the image is continuous using: inputImage.isContinuous(). It returns a bool. It should be true. 2) If the image is not continuous, you can create a copy of the image that it is by creating a clone of the image via inputImage.clone() . Behind the scenes, we are creating a deep copy of the input using the create method, that should guarantee that the new matrix is continuous.
//check image before continuing:
if ( !inputImage.isContinuous() ){
//if the image is not continuous, create a deep copy:
inputImage = inputImage.clone();
}

How can I stop async tasks that loops in background android after onPause() is called?

I'm using package com.hierynomus.smbj.share; to connect via smb2 to a network location in order to check it's connectivity however this only runs at the start of my activity (in background).
I've added a listener to return after the task has returned a string value (fail, success) once the the listener in the activity (i called the task from) is called, I then create a new instance of the Connection Status (this loops it)
This is how i check for the connection at onCreate() of an activity
//Global ConnectionStatus connectionStatus;
connectionStatus = new ConnectionStatus();
connectionStatus.setContext(this);
connectionStatus.setListener(this);
connectionStatus.setCon(databaseReadWrite.getMydbc());
connectionStatus.execute("CheckDatabase", "nodelay");
This is how I'm trying to cancel task when another activity is opened
protected void onPause() {
delay.equals("cancel");
super.onPause();
MyApplication.activityPaused();
if (connectionStatus != null) {
connectionStatus.cancel(true);
}
hasRun = false;
}
Then this runs in the same activity after the async task is completed so i've re-run a new instance of connectionStatus
#Override
public void onTaskCompleted(String result) {
ActionBar actionBar = this.getSupportActionBar();
String title = getTitle().toString();
String code = handlingFunctions.getResultCode(result);
if (code.equals("1")) {
Message.message(this, " Database connected to server!");
setTitle(title + result);
} else if (code.equals("2")) {
actionBar.setBackgroundDrawable(new ColorDrawable(Color.RED));
alertDialog.message(this, result);
} else if (code.equals("0")) {
actionBar.setBackgroundDrawable(new ColorDrawable(Color.RED));
setTitle(title + " Database connected in offline mode");
alertDialog.message(this, result);
} else if (code.equals("3")) {
//alertDialog.message(this, result);
imageStatus.setText(result);
} else if (code.equals("4")) {
imageStatus.setText(result);
}
connectionStatus = new ConnectionStatus();
connectionStatus.setContext(getApplicationContext());
connectionStatus.setListener(AllParts.this);
connectionStatus.setCon(databaseReadWrite.getMydbc());
connectionStatus.execute("CheckDatabase", "delay");
}
}
public class ConnectionStatus extends AsyncTask<String, Void, String> {
private OnConnectionStatusComplete listener;
private ArrayList<String> imageNames;
private ArrayList<ImageDetails> currentImageDetails;
private SQLiteConnection sqLiteConnection;
private Context context;
public void setListener(OnConnectionStatusComplete listen) {
this.listener = listen;
}
public void setImageNames(ArrayList<String> ImageNames) {
this.imageNames = ImageNames;
}
public void setCurrentDetails(ArrayList<ImageDetails> details) {
this.currentImageDetails = details;
}
#Override
protected void onPostExecute(String s) {
listener.onTaskCompleted(s);
}
public void setContext(Context mContext) {
context = mContext;
}
public void setCon(SQLiteConnection sqlite) {
sqLiteConnection = sqlite;
}
#Override
protected String doInBackground(String... strings) {
if(this.isCancelled()){
return "";
}else{
MyApplication myApplication = (MyApplication) context.getApplicationContext();
String IPAddress = myApplication.getIpaddress();
String domain = myApplication.getDomainname();
String username = myApplication.getUsername();
String password = myApplication.getPassword();
String containingFolder = myApplication.getSharefolder();
String temp = "";
//return null;
if (strings[1].equals("delay")) {
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (strings[0].equals("CheckDatabase")) {
temp = checkDatabaseConnect();
} else {
temp = checkImageConnection(IPAddress, domain, username, password, containingFolder);
}
return temp;
}
}
String checkDatabaseConnect() {
String statement = "PRAGMA sync_status";
JSONArray is_ready = new JSONArray();
try {
SQLiteStatement mystatement = null;
try {
mystatement = sqLiteConnection.prepareStatement(statement);
} catch (SQLException ex) {
try {
java.io.File path = new java.io.File("/sdcard/exports/logs");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String currentDateTime = dateFormat.format(new Date()) + " ";
java.io.File myFile = new java.io.File(path, "DBCrashes.txt");
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("\n" +
"\r");
myOutWriter.append(currentDateTime + "Get pragma results: (" + statement + ")" + ex);
myOutWriter.close();
fOut.close();
} catch (java.io.IOException e) {
//do something if an IOException occurs.
}
}
mystatement.step();
int ncols = mystatement.getColumnCount();
if (ncols > 0) {
String result = mystatement.getColumnTextNativeString(0);
JSONObject jObject = new JSONObject(result);
is_ready = jObject.getJSONArray("peers");
if (is_ready.length() > 0) {
return "Success, Database is connected! (1)";
} else {
return "The database is not connected to the server. In offline mode, check network and restart application to connect to server. (0)";
}
}
mystatement.dispose();
} catch (SQLException ex) {
try {
java.io.File path = new java.io.File("/sdcard/exports/logs");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String currentDateTime = dateFormat.format(new Date()) + " ";
java.io.File myFile = new java.io.File(path, "DBCrashes.txt");
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("\n" +
"\r");
myOutWriter.append(currentDateTime + " (" + statement + ")" + ex);
myOutWriter.close();
fOut.close();
return "No connection to a database, please try again (2)";
} catch (java.io.IOException e) {
//do something if an IOException occurs.
}
} catch (JSONException e) {
e.printStackTrace();
}
return "Success (5)";
}
}
The problem I'm having is after I leave the activity, the task is still running and returns this error (I know this because it takes into account the delay)
You do have implemented a handling for isCanceled but this implementation is only at the start.
Your current flow is like this:
task starts, immediately checks if it is cancelled or not (since it is the first line in doInBackground)
onPause is called, cancel of the task is invoked
since the cancel check has already been made your task continues to run freely
How do you solve this?
The easiest way would be to check if it is cancelled before checkDatabaseConnection or checkImageConnection is called. And even inside those methods check if it is cancelled or not.
Even if that is done correctly, your Thread.sleep could cause your AsyncTask being cancelled 6s after onPause is called.
For reasons like this, AsyncTask is not used anymore. There are other options for Threading which are much better.
This or this will give you a starting point.
try checking if the task is cancelled after the Thread.sleep(6000) , so even if the task was in sleep when cancel is called it will return when it is done.
if (strings[1].equals("delay")) {
try {
Thread.sleep(6000);
if(this.isCancelled()) {
return "";
}
} catch (InterruptedException e) {
e.printStackTrace();
}
/*if(this.isCancelled()) {
return "";
}*/
}

How to wait first for the retrofit response before returning the boolean

always returning the wrong value, before the request has been finish. The validation will already return the value without waiting for the response. I'am using retrofit for request then i put it on listener.
Thankyou for the help, suggestion is much accepted!.
this is my code, i have validation for the screen when it's true it will goes to another screen.
#Override
public boolean isValid() {
if (NetworkUtils.isConnected(getActivity())) {
final AtomicBoolean pass = new AtomicBoolean(false);
Thread simpleThread = new Thread() {
public void run() {
new ReprintOnlineHelper(rType, receiptNoEditText.getText().toString(), issuedDate, etTotalAmtPaid.getText().toString(), new ReprintOnlineHelper.ReceiptNoSearchListener() {
#Override
public boolean onServiceResponse(List<ReceiptNumber> receiptNumbers) {
Log.e("receiptNumbers", "" + receiptNumbers.get(0).getTPAYRECEIPTNO());
if (receiptNumbers.isEmpty()) {
returnValue = "eReceipt Number not found!";
val = true;
} else {
String pdates = null, ddates;
try {
if (!receiptNumbers.get(0).getTPAYISSUEDDATE().isEmpty()) {
Date periodFormat = df.parse(receiptNumbers.get(0).getTPAYISSUEDDATE());
pdates = sdf.format(periodFormat);
}
} catch (ParseException e) {
e.printStackTrace();
Log.e("ddd", "" + e.getMessage());
}
String tinNo = receiptNumbers.get(0).getTPTIN();
if (tinNo.contains("-")) {
tinNo = receiptNumbers.get(0).getTPTIN().replace("-", "");
}
Log.e("JAC", "" + receiptNumbers.get(0).getTPAYRECEIPTNO() + "---" + AlfonzoUtils.formatDate(DateUtils.simpledateToMillis(pdates, DateUtils.DateFormat.SIMPLE_DATE_5_FORMAT)) + "---" + MoneyEditText.toDouble(receiptNumbers.get(0).getTOTALPAID()) + "--" + AlfonzoUtils.formatDate(issuedDate) + "--" + receiptNoEditText.getText().toString() + "--" + tinNo + "--"+revenueCollection.getTpTin().replace("-", ""));
if (receiptNumbers.get(0).getTPAYRECEIPTNO().equals(receiptNoEditText.getText().toString()) &&
AlfonzoUtils.formatDate(DateUtils.simpledateToMillis(pdates, DateUtils.DateFormat.SIMPLE_DATE_5_FORMAT)).contentEquals(AlfonzoUtils.formatDate(issuedDate))
&& MoneyEditText.toDouble(receiptNumbers.get(0).getTOTALPAID()) == MoneyEditText2.toDouble(etTotalAmtPaid.getText().toString()) && tinNo.equals(revenueCollection.getTpTin().replace("-", ""))) {
pass.set(true);
returnValue = "success";
val = true;
showMessagePrompt(rType,returnValue);
return true;
} else if (!tinNo.equals(revenueCollection.getTpTin().replace("-", ""))) {
returnValue = "eReceipt Number was not issued to this TIN " + revenueCollection.getTpTin();
val = false;
} else if (!AlfonzoUtils.formatDate(DateUtils.simpledateToMillis(pdates, DateUtils.DateFormat.SIMPLE_DATE_5_FORMAT)).contentEquals(AlfonzoUtils.formatDate(issuedDate))) {
returnValue = "Issued date is not valid";
val = false;
} else if (MoneyEditText.toDouble(receiptNumbers.get(0).getTOTALPAID()) != MoneyEditText2.toDouble(etTotalAmtPaid.getText().toString())) {
returnValue = "Total amount paid is not valid";
val = false;
} else if (!receiptNumbers.get(0).getTPAYRECEIPTNO().equals(receiptNoEditText.getText().toString())) {
returnValue = "ReceiptNo is not valid";
val = false;
}
}
return false;
}
#Override
public void onErrorResponse(int err) {
}
}).reprintReceiptNo();
}
};
if (!receiptNoEditText.getText().toString().isEmpty() && issuedDate != 0 /*&& MoneyEditText2.toDouble(etTotalAmtPaid.getText().toString()) > 0*/) {
try {
simpleThread.start();
simpleThread.join();
pass.get();
Log.e("pass", "" + pass + "-" + pass.get() + val);
} catch (InterruptedException e) {
e.printStackTrace();
}
return pass.get();
}
}
return false;
}
this is my request in retrofit:
public void reprintReceiptNo() {
JSONObject jO = new JSONObject();
JSONObject result = new JSONObject();
JSONArray jsonArray = new JSONArray();
try {
jO.put("xReceipt", receiptTypeNo);
jO.put("xType", receipttype);
jsonArray.put(jO);
result.put("dataArray", jsonArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("dataArray", "----- " + result.toString());
ServiceInterface si = BaseRestClient.getClient();
Observable<List<ReceiptNumber>> call = si.getreprintReceiptNumber(result.toString());
call.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<ReceiptNumber>>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(List<ReceiptNumber> receiptNumbers) {
Log.e("receiptNumbers", "" + receiptNumbers.toString());
onReceiptNoSearchListener.onServiceResponse(receiptNumbers);
}
});
}
Its not possible for the isValid() method to wait for the service reponse if you have code outside the Thread you've created.
The method will execute the Thread, but while that Thread is executing, the rest of the code will be read, meaning the return pass.get(); or the return false; statments will be read, causing the the method to return before the server response.
The solution its to change the way this was done. You should check if you can call the server and then created your logic in the methods onServiceResponse() and onErrorResponse() based on how you want to proceed.

Call an AsyncTask subclass of activity from another class?

I know this kind of questions are maybe too old, but I got stock with this silly thing.
I have an AsyncTask class which is a subclass of an activity class, and right now I want to call it from another class: following codes shows what I mean:
public class STA extends Activity {
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
private static final String TAG = "ListSpdFiles: ";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private String initiator;
private String path;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(String initiator, String path) {
this.initiator = initiator;
this.path = path;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(getApplicationContext(), pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
// tv.setText("task concluded with a null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
//tv.setText("List of files received is:\n" + Arrays.toString(listOfFiles));
}
term();
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
final Global globalVariable = (Global) getApplicationContext();
if (globalVariable.getPasswordButt() == false) {
// Calling Application class (see application tag in AndroidManifest.xml)
// Get name and email from global/application context
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
String username = "/" + getLastAccessedBrowserPage() + ".username" + ".txt";
//String password = "/" + CurrentURL + "password" + ".txt";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pcas.readFile(initiator, username, baos);
Log.i(TAG, "OutputStreampassword: "
+ new String(baos.toByteArray()));
String name = new String(baos.toByteArray());
if (!name.equalsIgnoreCase("")) {
globalVariable.setUsername(name);
// getCurrentInputConnection().setComposingText(name, 1);
// updateCandidates();
}
globalVariable.setIsUsername(false);
} else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
// globalVariable.setUsernameButt(false);
} else if (globalVariable.getPasswordButt() == true) {
// Calling Application class (see application tag in AndroidManifest.xml)
// final Global globalVariable = (Global) getApplicationContext();
// Get name and email from global/application context
final boolean ispassword = globalVariable.getIsPassword();
if (ispassword == true) {
// String username = "/" + CurrentURL + "username" + ".txt";
String password = "/" + getLastAccessedBrowserPage() + ".password" + ".txt";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pcas.readFile(initiator, password, baos);
Log.i(TAG, "OutputStreampassword: "
+ new String(baos.toByteArray()));
String name = new String(baos.toByteArray());
if (!name.equalsIgnoreCase("")) {
globalVariable.setPassword(name);
//getCurrentInputConnection().setComposingText(name, 1);
// updateCandidates();
}
globalVariable.setIsPassword(false);
} else if (ispassword == false)
Log.i(TAG, "Wrong Input Type For Password.");
globalVariable.setPasswordButt(false);
// boolpassword=false;
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = getContentResolver().query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
Would you please tell me what should I do to fix this code?
Looking over the code I did not see anywhere you referenced anything from the Activity itself besides the application context so you can move the ListSpdFiles class to its own java file and pass it a context into the constructor when you make a new instance of it.
Put this class in a ListSpdFiles.java file so it is no longer an inner class.
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
Context applicationContext;
public ListSpdFiles(Context context, String initiator, String path) {
this.initiator = initiator;
this.path = path;
applicationContext = context.getApplicationContext();
}
// The rest of your code still goes here. Replace other calls to
// getApplicationContext() with the new applicationContext field
}
You can now use this class anywhere a Context is available. You create a new instance by doing:
ListSpdFiles listSpdFilesTask = new ListSpdFiles(context, "someInitiator", "somePath");
listSpdFilesTask.execute();

ownCloud Android DownloadRemoteFile File Name

I'm trying to download a list of RemoteFiles in Android using ownCloud. I can download the files perfectly fine but I'd like to notify the user when a file finishes. I'm downloading an entire directory:
#Override
public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
if (operation instanceof ReadRemoteFolderOperation) {
if (result.isSuccess()) {
Toast.makeText(this, "Finished reading folder", Toast.LENGTH_SHORT).show();
for (Object o : result.getData()) {
RemoteFile remoteFile = (RemoteFile) o;
String remotePath = remoteFile.getRemotePath();
File targetDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/owncloud_download");
downloadHelper.downloadFile(remoteFile, targetDirectory);
}
}
}
if (operation instanceof DownloadRemoteFileOperation) {
if (result.isSuccess()) {
// Notify the user here that the file finished
}
}
}
I've looked at the ownCloud library source but can't seem to find what a DownloadRemoteFileOperation returns as a result other than a boolean indicating success and an HTTP status code. I thought it might be in result.getLogMessage() but that just gives me an HTTP 200 status. How can I get the name of a file that's finished?
Edit: I also looked at result.getData() but that's null in a DownloadRemoteFileOperation.
Here's my workaround for the time being. I didn't want to modify the ownCloud library source (again) so instead I just do a check in onTransferProgress like so:
#Override
public void onTransferProgress(long rate, long transferred, long total, String fileName) {
if (transferred == total) {
runOnUiThread(new Runnable() {
// do the update here, file name is available
}
}
}
Here's another option. I needed the file being uploaded if the upload failed so I modified the ownCloud library source. This way I could return file names in the RemoteOperationResult.
RemoteOperationResult.java:
private String fileName;
public String getFileName() {
return fileName;
}
public void setFileName(String name) {
fileName = name;
}
DownloadRemoteFileOperation.java
#Override
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result = null;
/// download will be performed to a temporal file, then moved to the final location
File tmpFile = new File(getTmpPath());
/// perform the download
try {
tmpFile.getParentFile().mkdirs();
int status = downloadFile(client, tmpFile);
result = new RemoteOperationResult(isSuccess(status), status,
(mGet != null ? mGet.getResponseHeaders() : null));
Log_OC.i(TAG, "Download of " + mRemotePath + " to " + getTmpPath() + ": " +
result.getLogMessage());
} catch (Exception e) {
result = new RemoteOperationResult(e);
Log_OC.e(TAG, "Download of " + mRemotePath + " to " + getTmpPath() + ": " +
result.getLogMessage(), e);
}
// Added this line
result.setFileName(mRemotePath);
return result;
}
UploadRemoteFileOperation.java:
#Override
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result = null;
try {
// / perform the upload
synchronized (mCancellationRequested) {
if (mCancellationRequested.get()) {
throw new OperationCancelledException();
} else {
mPutMethod = new PutMethod(client.getWebdavUri() +
WebdavUtils.encodePath(mRemotePath));
}
}
int status = uploadFile(client);
if (mForbiddenCharsInServer){
result = new RemoteOperationResult(
RemoteOperationResult.ResultCode.INVALID_CHARACTER_DETECT_IN_SERVER);
} else {
result = new RemoteOperationResult(isSuccess(status), status,
(mPutMethod != null ? mPutMethod.getResponseHeaders() : null));
}
} catch (Exception e) {
// TODO something cleaner with cancellations
if (mCancellationRequested.get()) {
result = new RemoteOperationResult(new OperationCancelledException());
} else {
result = new RemoteOperationResult(e);
}
}
// Added this line
result.setFileName(mLocalPath);
return result;
}

Categories

Resources