I'm sending a temporary file as a response to a request using the ktor library on a android tablet, but I can't find a way to safe delete it after being sent (or something went wrong).
How can I make sure that this file was delete without interrupting the sending process? Maybe using some callback or method that I´m not aware of.
Update: answering comments:
my code:
try {
call.response.headers.append("entity-count", entityCount)
call.response.headers.append("sync-length", lenght)
call.respondFile(FileContent(file) // need to delete this file after sent OR failed
} catch (e: Exception) {
Log.e(TAG, e)
}
should I just add a file.delete() line inside a finally block?
I think my main question/confusion (coming from java world) its if respondFile is a blocking call or not. If it its, just adding file.delete on finally block will be fine, otherwise I need to register somme kind of onCompleted callback.
You can use finally: it will be called after sending the file or in case of an error
try {
call.response.headers.append("entity-count", entityCount)
call.response.headers.append("sync-length", lenght)
call.respondFile(FileContent(file) // need to delete this file after sent OR failed
} catch (e: Exception) {
Log.e(TAG, e)
} finally {
file.delete()
}
Related
I'm in trouble with azure synchronization, I'm able to detect the number of pending operations by mCLient.getSyncContext().getPendingOperations(); but can't resolve them. Any help or suggestion?
When working with in an offline scenario and you have pending operations, you can push them to the server by using the push() function.
It would look something like the following:
try {
MobileServiceSyncContext syncContext = mClient.getSyncContext();
syncContext.push().get();
// here you would do a pull on any table you want to grab data from
}
catch (final MobileServiceConflictException e)
{
// the server item causing the exception can be obtained by calling e.getItem()
JsonObject serverObject = e.getItem();
// on the sync context, call one of the following:
// .cancelAndDiscardItem() to cancel update and discard local item
// .cancelAndUpdateItem() to update the local item with the server's copy
// .cancelAndUpdateItem(JsonObject item) to update the server's item w/ the local
// make sure to call push() again on the sync context
}
All in all - make sure you call push() on the MobileServiceSyncContext and then handle any MobileServiceConflictException that may return.
If I catch for MobileServiceConflictException android studio tells me that the Exception is never thrown in this corresponding try block.
try {
MobileServiceSyncContext syncContext = mClient.getSyncContext();
syncContext.push().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (MobileServiceConflictException e) {
}
I am trying to download a file using the Box android SDK. The problem seems to be with the destinationFile parameter. The box.com call is checking whether the destinationFile exists - but why? I get java.io.FileNotFoundException.
destinationFile = new File(getFilesDir(), "myfile.crs");
// destinationFile = new File(getFilesDir(),"/");
try {
BoxDownload fileDownload = mFileApi.getDownloadRequest(destinationFile, fileID)
// Optional: Set a listener to track download progress.
.setProgressListener(new ProgressListener() {
#Override
public void onProgressChanged(long numBytes, long totalBytes) {
// Update a progress bar, etc.
}
})
.send();
} catch (BoxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
To do All the checks
Log.i(getClass().getName(),"Does File exists:"+(destinationFile.exists()?"Yes":"No"));
Log.i(getClass().getName(),"Is it A file:"+(destinationFile.isFile()?"Yes":"No"));
Log.i(getClass().getName(),"Is it Writable:"+(destinationFile.canWrite()?"Yes":"No"));
Log.i(getClass().getName(),"Is it A Readable:"+(destinationFile.canRead()?"Yes":"No"));
Log.i(getClass().getName(),"Path:"+destinationFile.getAbsolutePath());
you are most likely to found file does not exists then do this before using it.
if(!destinationFile.exists()){
try {
destinationFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
The answer was to create a new File. Then call .createNewFile() on the File instance. Then call all of the code I posted except to put run it in the background. That's why I was asking here - I was wondering if I was doing something incorrect for Android and I was. Box networking operations need to be done on a thread.
Too bad they never show this for downloading a file. Too bad there's not one example of downloading a file with the Android DSK on the web.
I am using Acralyzer for reporting of errors (Crash reports)
Now I want to manually send a Custom report to Acra.
But do not know , how to do ?
Try this:
try
{
// some code
}
catch (Exception e) {
ErrorReporter.getInstance().handleException(e);
}
I'm using usb-serial-for-android library and I am getting some strange results. After 2.5 hours of continuous communicating with the serial port and reading and writing successfully, I get this exception:
exception in UsbManager.openDevice
android.os.TransactionTooLargeException
at android.os.BinderProxy.transact(Native Method)
at android.hardware.usb.IUsbManager$Stub$Proxy.openDevice(IUsbManager.java:339)
at android.hardware.usb.UsbManager.openDevice(UsbManager.java:255)
at com.hoho.android.usbserial.driver.UsbSerialProber$1.probe(UsbSerialProber.java:63)
at com.hoho.android.usbserial.driver.UsbSerialProber.probeSingleDevice(UsbSerialProber.java:174)
But when i force close my app and then restart it, everything is fine and my app can communicate with the port again.
It maybe useful to mention that before the exception , I get this exception:
java.io.FileNotFoundException: /sdcard/log.txt: open failed: EMFILE (Too many open files)
at libcore.io.IoBridge.open(IoBridge.java:406)
at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
at java.io.FileWriter.<init>(FileWriter.java:58)
at org.example.myapp.util.L.log(L.java:32)
I use class L for logging purposes:
public class L {
public synchronized void log(String message){
File logFile = new File("sdcard/log.txt");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(new Date(DateProvider.getInstance().getCurrentDateAsMillisecs()).toString()+": "+message);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
It seems that some kind of buffer or cache is getting filled and prevents communicating with the device.
How can I get rid of the exception?
Update:
Writing to log file never fails even though I'm getting the exception. It only affects communicating with usb device.
You are opening too many files.
Problems I have found:
- You never close logFile
- You open the file in the log function, a static File would be better and could be initialized in a log_init(); function.
Or, make logFile an object variable and initialize it in the constructor.
I think solving these will solve your problem.
Can you not use getFilesDir() to pass the directory path while creating file
public class L {
public static File logFile = new File("sdcard/log.txt");
public synchronized void log(String message){
....
Everytime you call new File you request a file resource from the system. As you keep doing it the system will complain that you opened too many files. To avoid this, request the file only once.
Following suggestions on this site, I have adopted SimpleXML from org.simpleframework.xml.
I use this code to deserialize my class from a file on disk:
try {
myPoints = serial.read(Points.class, new File(getFilesDir(), "points.xml"));
Log.i(TAG, "Number of Points: " + myPoints.getSize());
} catch (FileNotFoundException e) {
Log.d(TAG, "No data found!");
} catch (Exception e) {
Log.d(TAG, "Uncaught exception: ", e.getMessage());
}
In the event the contents of file "points.xml" is not legal xml (in my case it's an empty file), serial.read breaks (an exception occurs in Persister.class, sorry I don't have simplexml sources...).
Should I check for xml consistency beforehand?
Can anybody help?
No need to validate before-hand since you won't be able to fix the problem. Just make sure it fails gracefully (as your code appears to be doing).
You may, however, want to see if the file is empty or not in the case of a deserialization error. An empty file is likely not a problem where as a malformed XML file is!