Android. onPostExecute with several try-catch blocks - java

First of all, I have almost no experience in Java. I'm using AsyncTask to get some data from my server and in the onPostExecute method I need to use several try-catch blocks to manage the received data. If one of them fails (catch is executed) the app should stop execution and show a dialog. But when any catch block is executed, the following try-catch blocks are executed, and that's what I want to avoid. I can't use return because onPostExecute returns void.
So, what is the best way to manage this situation to achieve what I need?

If a Method returns Void, you can use "return;" to exit the method.
So in the Catch block, Show the Dialogand Exit with return;
Elsewhere you can catch different exceptions in one try block.

Related

Finally with callback listeners

So, I have the following code:
try{
....
if(serverResp.isSucces()){
callbackListener.onDataLoaded(serverResp);
}
}catch(Exception e){
//...do whatever I have to
}finally{
urlConnection.disconnect();
}
My question is, when the urlConnection.disconnect is being called? Most of the examples with finally explains when its called in case of return. I understand that case, but here I don't have return but to call to a listener.
In most cases the listener callback triggers a new Activity to start. I would like to be sure, that all my previous connections are closed down!
So the main question is:
When the finally get's called, if there is no return but listener callback?
Is this a proper way to close the urlConnection?
finally is the best place to close resources.
The finally block is executed after the point in which the try/catch blocks are exited. This occurs when:
The end of the try block is reached
The try block is exited in any other way (break out of an outer loop, return, an uncaught exception is thrown, etc.)
An exception is caught and execution reaches the end of the catch block
The thread executing this code is terminated.
The only times that finally may not be executed are described here.
In your case, supposing no exceptions are thrown, your callback will be executed before the connection is closed. The connection will be closed after the callback is complete (via full execution or delegatation to some other thread).
Note that disconnect may only be a safe way to ensure connections are closed in newer version of Java. You would normally attempt to read the entire response and then close the input stream. You can find numerous discussions about this on this site.

How to synchronously execute when using wait() function in Android?

While executing the following code in an Android App, the setText happens after mainActivity.notify() is called from another Service. So, it appears as if the mainActivity.wait() is getting executed before the setText, resulting in the setText getting waited.
What may be the reason for this and how to make the Toast execute before mainActivity.wait(), so that the setText is displayed while the MainActivity waits.
public static Activity mainActivity;
....
startButton.setText("Processing...");
synchronized(MainActivity.mainActivity) {
try {
mainActivity.wait();
} catch (InterruptedException e) {
}
}
startButton.setText("Start");
First off, never have a static reference to an Activity. That's an almost assured memory leak. If you think you need that, your entire app's architecture is almost certainly wrong, or you don't understand how to use Contexts.
Secondly, under the hood Android, like any other GUI OS, is driven by an event loop. By holding up the main thread, you prevent the event loop from executing thus freezing the entire app. In particular without running the event loop the application will never redraw.
Third, you cannot wait until a Toast appears. Toasts are displayed by the system itself, and it does so when it decides to- there may be other toasts on screen already, for example. There is no mechanism to be informed of when a toast is displayed. The purpose of a toast is fire and forget, if you need something more powerful you'll need to write it yourself.
You can use Thread.sleep method
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

How to check if one of the thread has failed?

I have a multi-threaded Java application. I want the whole application to fail is one of the thread encounters any exception.
I don't think doing System.exit(); inside the thread will exit the whole app.
Can someone suggest a way?
put try-catch in Thread's run method and in catch block System.exit(0); it works.
actually, calling System.exit() will exit the whole app, but that's generally not what you want in your library code (for instance, it makes unit testing difficult).
a better implementation is to have a shared "error handler" reference, with an implementation that you control. in unit tests, you could just log the exception. in your real app, you could call System.exit().
One simple way to do that is to have try{} catch{} on each thread, when you catch exception you may call static function that exits the application.

What might be the purpose of sleeping for just to see if the thread gets interrupted?

I came across some Java code that has a method containing the following:
static boolean waitForSeconds(long seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (InterruptedException ex) {
return false;
}
return true;
}
What might be the purpose of this? The return value is used to determine whether a computation should continue. It seems strange to me to try to sleep for 1 second for the sole purpose of checking whether the thread was interrupted during that second.
Is the code that calls this method trying to accomplish the same thing as thread.isInterrupted()? Whatever it is trying to do, is there a better way?
The call to waitForSeconds appears at the top of another method, not inside of a loop, so if this code does intend to wait for a second for some purpose in addition to checking for an interrupt, it seems like it would be checking in the wrong place. Wouldn't it be better to put the sleep near the loop, where it is clearer what it is doing?
For the last question, please reply here instead:
Is it clearer to sleep near a function call in a loop or in the function call itself?
The purpose is to pause.
Check the code calling the outer method to try to see why they want to pause.
They may want to save CPU or network.
The purpose of the method is to cause the thread execution to stop for the specified number of seconds. The catch clause allows the method to communicate to the caller that the thread was interrupted, as opposed to the time period expiring.
The idea is probably to introduce a pause in the computation, but if the pause is interrupted, then that means that the computation should not continue. Why a pause is needed is impossible to say without seeing the surrounding (calling) code.
I guess they want to pause for at least x seconds; if for some reason the Thread was unable to sleep that long, they'd use the return value to call the method again

Is there possibility that a finally block might not execute? [duplicate]

This question already has answers here:
Does a finally block always get executed in Java?
(51 answers)
Closed 2 years ago.
We know that no matter whether an exception is thrown, or caught and handled it, the finally block will get executed, So I was curious that is there any possibility that finally block will not executed.
And if System.exit() is called either in try or catch, then also will the finally gets called?
If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
Source: java.sun.com: Java Tutorial: The finally Block
System.exit() will prevent a finally block from executing.
In the Java documentation:
http://java.sun.com/docs/books/tutorial/essential/exceptions/finally.html
It explains Finally very well.
They do note that if the JVM exits, that the finally block will not be called. Or if a thread that is running the block of code gets killed, the finally block will not be called. In all other cases it will.
One thing I can think of right now is an OutOfMemoryError in which case there is a chance that no further code in your app can be executed.
try {
System.out.println("BEFORE");
System.exit(0);
System.out.println("AFTER");
} finally {
System.out.println("FINALLY");
}
this will give you the output:
BEFORE
System.exit(1); you can use
If some Java Native Interface method segfaults (a library function outside of java but called from there crashes) a finally method will also not be called because the entire JVM stops.
Errors in the JVM itself also result in a crash and prevent everything from continued execution.
the finally clause in the try-catch exception block always executes, irrespective of the occurrence of exception in the normal java program flow. If the execution flow is stopped before the finally clause then the finally block will not be executed.
we can use System.exit(1); before finally block and stop the execution flow of the program.
Another situation that I can think of (that is left out from the other answers) is when an exception is thrown inside a finally block, in that case the finally block will not be "completely" executed.

Categories