Use of static variable associated with activity in async task - android

I have an activity A with static variable s. I pass the activity instance to async task for some processing. Suppose, in the mean time activity is closed (garbage collected) by android OS and AsyncTask is running in background. In AsyncTask now it is trying to access A.s which is not available so, it throws an exception. Is there any Solution for this. Thanks in advance.

Stop the asyncTask when the activity is closed. So the asyncTask will not try to access the activity anymore.

Try the following, don't keep s as static just pass it to the doInBackground method and collect back the result from onPostExecute method .
private class someLongRunningOperation extends AsyncTask<ArrayList, Progress, Result>{
#Override
protected Result doInBackground(ArrayList... params) {
// TODO Auto-generated method stub
String s=params[0];
//Do operations on the data
...
return s;
}
}
Call:
someLongRunningOperation longTask= new someLongRunningOperation ();
longTask.execute(yourList1, yourList2, yourList3...);
Note that the problem that you described can also happen during the screen orientation changes, If you are using a fragment use
setRetainInstance(true);
to save your data across activity recreations.

Just add null checks to avoid the exception. Example:
if (A != null && A.s != null) {
// proceed with your attempt to update the A.s variable
}

Related

Android: How to retrieve values from an AsyncTask?

I've been researching all day trying to find out how to retrieve the values computed in the doInBackground async task. No luck at all.
I'm doing a basic HttpURLConnection request and parsing some XML data from a webpage using the DOM. I successfully store the data in two different arrays
///////////inside doInBackground:
for(int x=0; x<10; x++)
{
username[x] = element.getFirstChild().getNodeValue();
score[x] = anotherElement.getFirstChild().getNodeValue();
}
Now, all I want to do is simply output the values onto a textView.
Among many other things, I have attempted:
protected void onPostExecute(String result)
{
for (int xx = 0; xx<10; xx++)
{
theMainTextView.append(username[xx] + " scored " + score[xx] +"\n");
}
}
Nothing I have attempted works. A recurring error I'm receiving is the NullPointerException. Am I doing something dramatically incorrect? Know of any other (even obscure) methods I could try? Ignore the for loops if that helps...I've omitted a lot of code. Just assume I want to retrieve two values...a username and a score.
Edit: I should probably mention that the AsyncTask ends with return null;
Edit: apparently the code is not faulty but I had a globally declared button which was causing a null Pointer Exception. Sorry about that.
If you get a NullPointerException as stated in the question and this is all of your onPostExecute() code than the field theMainTextView must be null.
You must initialize it before starting the AsyncTask - best place to do so is in onCreate() for Activities or onCreateView() for Fragments.
Although it's not the best practice, your code should work. I think the problem comes from another part. Can you please specify what line is throwing the NullPointerException?
To retrieve values from an AsyncTask you can use listener.
First create interface listner (new file):
public interface AsyncListener {
void onAsyncFinishMethod(String params);
}
Second, use implement for your main class where you call async task (example)
public class MainActivity implements AsyncListener {
Third, create full body for listener method in your main class. You are overriding method from interface. So if you change params you will have to change too in interface. Here you will get all results after task finish and call onPostExecute.
#Override
public void onAsyncFinishMethod(String params) {
Log.d("xxx", params);
}
Fourth, set listener for your async task. It means: In your async task class create this method
public void setOnAsyncFinishedMethod(AsyncListener listener) {
this.listener = listener;
}
Make sure, your async task has private param with type that listener
private AsyncListener listener;
In onPostExecute in async task class call listener method as a last (if you don't have this method, please create it)
#Override
protected void onPostExecute(String params) {
listener.onAsyncFinishMethod(param);
}
Last step, during calling async task in your main class don't forget bind setOnAsyncFinishedMethod method to it
My Example:
private void runMyAsyncTask() {
CustomAsync async = new CustomAsync();
async.setOnAsyncFinishedMethod(this);//<<< before execute use setOnAsyncFinishedMethod
thread.execute();
}
Of course, params used in onAsyncFinishedMethod could be different than you, also onPostExecute.

Return value from AsyncTask class onPostExecute method

Ok so now I have Class A that contains some spinners that values will be populated by Class B that extends AsnycTask which grabs the spinner values from a web service. In class B i manage to retrieve the values, showing in a Toast. The problem now is how do I pass those spinner values back to Class A?
I've tried
Can OnPostExcecute method in AsyncTask RETURN values?
by passing Class A to Class B and store the value in a public variable of Class A like below
#Override
protected void onPostExecute(String result)
{
classA.classAvariable = result;
}
However whenever I try to read the classAvariable i always get a NullPointer Exception.
Seems like the variable was never assigned with the result.
For readability purpose I needed to seperate Class B instead of using as an inline class.
Any ideas my fellow Java programmers?
Problem here is that when you execute your AsynchTask, its doInBackground() methode run in separate thread and the thread that have started this AsynchTask move forward, Thereby changes occur on your variable by AsynchTask does not reflect on parent thread (who stated this AsynchTask) immediately.
Example --
class MyAsynchTask
{
doInbackground()
{
a = 2;
}
}
int a = 5;
new MyAsynchTask().execute();
// here a still be 5
Create a interface like OnCompletRequest() then pass this to your ClassB constructor and simply call the method inside this interface such as complete(yourList list) in the method of onPostExecute(String result)
You can retrieve the return value of protected Boolean doInBackground() by calling the get() method of AsyncTask class :
E.g. you have AsyncTask class as dbClass like
dbClass bg = new dbClass(this);
String Order_id = bg.execute(constr,data).get();
Here I am passing constr as URL and data as string of inputs to make my class dynamic.
But be careful of the responsiveness of the UI, because get() waits for the computation to complete and will block the UI thread.

Android How to reconnect to AsyncTask after onDestroy() and relaunch onCreate()?

I have tested the statement that AsyncTasks are not destroyed along with their launching activity. And it is true.
I made the AsyncTask just publish a Log.i() message every 3 seconds for 1 minute. And I put Log.i() messsage in the onDestroy() method of the activity.
I see the activity is destroyed, but the AsyncTask keeps running until it finishes all 20 Log.i() messages.
And I am confused.
What if the AsyncTask had publishProgress() into the destroyed UI?
I guess some sort of exception would occurr, right?
What if the AsyncTask stores data in a global variable of class Application?
No idea here, NullPointer exception?
What if the app is restarted?
It will probably launch a new AsyncTask. Can it reconnect with the still running AsyncTask?
Is the AsyncTask immortal after the mother app is destroyed?
Maybe yes, how do all LogCat apps keep logging messages while the UI application is not visible anymore, maybe destroyed? And when you reopen them they show you the messsages that were generated while it was 'dead'.
All this seems like a discussion, but the question is in the title. I have this orphan AsyncTask, which I would like very much to reconnect to when the app is relaunched, but I don't know how to do it.
I forgot to tell why this is very important. The app gets destroyed when an orientation change occurs. And I don't want to loose the data produced by the AsyncTask, I don't want to stop it and restart it. I just want it to keep going and reconnect after the orientation changes are done.
I hope I've got this right as it's from some old code I no longer use (I now use an IntentService to do what this used to do).
This is what I originally had when I downloaded files in my main Activity...
public class MyMainActivity extends Activity {
FileDownloader fdl = null;
...
// This is an inner class of my main Activity
private class FileDownloader extends AsyncTask<String, String, Boolean> {
private MyMainActivity parentActivity = null;
protected void setParentActivity(MyMainActivity parentActivity) {
this.parentActivity = parentActivity;
}
public FileDownloader(MyMainActivity parentActivity) {
this.parentActivity = parentActivity;
}
// Rest of normal AsyncTask methods here
}
}
The key is to use onRetainNonConfigurationInstance() to 'save' the AsyncTask.
Override
public Object onRetainNonConfigurationInstance() {
// If it exists then we MUST set the parent Activity to null
// before returning it as once the orientation re-creates the
// Activity, the original Context will be invalid
if (fdl != null)
fdl.setParentActivity(null);
return(fdl);
}
I then have a method called doDownload() which is called from onResume() if a Boolean indicating downloadComplete is true. The Boolean is set in the onPostExecute(...) method of FileDownloader.
private void doDownload() {
// Retrieve the FileDownloader instance if previousy retained
fdl = (FileDownloader)getLastNonConfigurationInstance();
// If it's not null, set the Context to use for progress updates and
// to manipulate any UI elements in onPostExecute(...)
if (fdl != null)
fdl.setParentActivity(this);
else {
// If we got here fdl is null so an instance hasn't been retained
String[] downloadFileList = this.getResources().getStringArray(R.array.full_download_file_list);
fdl = new FileDownloader(this);
fdl.execute(downloadFileList);
}
}

Can OnPostExcecute method in AsyncTask RETURN values?

I am developing an Android application which requires the use of AsyncTask for Network connection. I called it from the main thread. So the doInBackground method runs and then returns to the onPostExecute method. After the onPostExecute method is executed, I want to return a value back to the activity from where it was called, as I have to some operation in that particular activity which requires the value returned from onPostExecute method.
How do I solve this? How do I return a value from onPostExecute ?
Thanks in Advance
AsyncTask, as its name stated, is running asynchronously with UI thread, the onPostExecute method will be called at some point in the future, when doInBackground finished. We don't care when onPostExecute method will be called (actually there is no way to tell at project build time), the only thing we care is onPostExecute method is guaranteed to be called properly by underlying framework at some point in the future. So the purpose of onPostExecute method is for processing result returned from worker thread, this is also why the only argument of onPostExecute method is the result returned from doInBackground method.
I have to some operation in that particular activity which requires the value returned from onPostExecute method. How do I solve this?
Of cause, you can create some instance variables (or use listerner pattern) in the Activity class store the result when returned and ready in onPostExecute method. The problem is you never know when this result is ready outside onPostExecute method at project build time, as it is actually determined at app runtime. Unless you write some waiting mechanism continuously polling the result, which resulting sacrifice the benefit of AsyncTask, for instance, the built-in API AsyncTask.get() which makes AsyncTask running synchronously with UI thread and return the result to the Activity.
The best practice is change your design and move the operation code which requires the result returned from AsyncTask into onPostExecute method. hope this helps.
you can use getter and setter for getting value back from AsyncTask
public class MainActivity extends Activity {
public String retunnumfromAsyncTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layouttest);
new Asyntask(this).execute();
}
public class Asyntask extends AsyncTask<Void, Void, String> {
private final Context Asyntaskcontext;
public Asyntask(Context context){
Asyntaskcontext = context;
}
#Override
protected void onPostExecute(String result) {
MainActivity mainactivity = (MainActivity) Asyntaskcontext;
mainactivity.retunnumfromAsyncTask = result;
super.onPostExecute(result);
}
}
}
Just write the AsyncTask class as inner class to your activity then, declare whatever the value you want to return as global. Was it helpful to you?

Background task, progress dialog, orientation change - is there any 100% working solution?

I download some data from internet in background thread (I use AsyncTask) and display a progress dialog while downloading. Orientation changes, Activity is restarted and then my AsyncTask is completed - I want to dismiss the progess dialog and start a new Activity. But calling dismissDialog sometimes throws an exception (probably because the Activity was destroyed and new Activity hasn't been started yet).
What is the best way to handle this kind of problem (updating UI from background thread that works even if user changes orientation)? Did someone from Google provide some "official solution"?
Step #1: Make your AsyncTask a static nested class, or an entirely separate class, just not an inner (non-static nested) class.
Step #2: Have the AsyncTask hold onto the Activity via a data member, set via the constructor and a setter.
Step #3: When creating the AsyncTask, supply the current Activity to the constructor.
Step #4: In onRetainNonConfigurationInstance(), return the AsyncTask, after detaching it from the original, now-going-away activity.
Step #5: In onCreate(), if getLastNonConfigurationInstance() is not null, cast it to your AsyncTask class and call your setter to associate your new activity with the task.
Step #6: Do not refer to the activity data member from doInBackground().
If you follow the above recipe, it will all work. onProgressUpdate() and onPostExecute() are suspended between the start of onRetainNonConfigurationInstance() and the end of the subsequent onCreate().
Here is a sample project demonstrating the technique.
Another approach is to ditch the AsyncTask and move your work into an IntentService. This is particularly useful if the work to be done may be long and should go on regardless of what the user does in terms of activities (e.g., downloading a large file). You can use an ordered broadcast Intent to either have the activity respond to the work being done (if it is still in the foreground) or raise a Notification to let the user know if the work has been done. Here is a blog post with more on this pattern.
The accepted answer was very helpful, but it doesn't have a progress dialog.
Fortunately for you, reader, I have created an extremely comprehensive and working example of an AsyncTask with a progress dialog!
Rotation works, and the dialog survives.
You can cancel the task and dialog by pressing the back button (if you want this behaviour).
It uses fragments.
The layout of the fragment underneath the activity changes properly when the device rotates.
I've toiled for a week to find a solution to this dilemma without resorting to editing the manifest file. The assumptions for this solution are:
You always need to use a progress dialog
Only one task is performed at a time
You need the task to persist when the phone is rotated and the progress dialog to be automatically dismisses.
Implementation
You will need to copy the two files found at the bottom of this post into your workspace. Just make sure that:
All your Activitys should extend BaseActivity
In onCreate(), super.onCreate() should be called after you initialize any members that need to be accessed by your ASyncTasks. Also, override getContentViewId() to provide the form layout id.
Override onCreateDialog() like usual to create dialogs managed by the activity.
See code below for a sample static inner class to make your AsyncTasks. You can store your result in mResult to access later.
final static class MyTask extends SuperAsyncTask<Void, Void, Void> {
public OpenDatabaseTask(BaseActivity activity) {
super(activity, MY_DIALOG_ID); // change your dialog ID here...
// and your dialog will be managed automatically!
}
#Override
protected Void doInBackground(Void... params) {
// your task code
return null;
}
#Override
public boolean onAfterExecute() {
// your after execute code
}
}
And finally, to launch your new task:
mCurrentTask = new MyTask(this);
((MyTask) mCurrentTask).execute();
That's it! I hope this robust solution will help someone.
BaseActivity.java (organize imports yourself)
protected abstract int getContentViewId();
public abstract class BaseActivity extends Activity {
protected SuperAsyncTask<?, ?, ?> mCurrentTask;
public HashMap<Integer, Boolean> mDialogMap = new HashMap<Integer, Boolean>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewId());
mCurrentTask = (SuperAsyncTask<?, ?, ?>) getLastNonConfigurationInstance();
if (mCurrentTask != null) {
mCurrentTask.attach(this);
if (mDialogMap.get((Integer) mCurrentTask.dialogId) != null
&& mDialogMap.get((Integer) mCurrentTask.dialogId)) {
mCurrentTask.postExecution();
}
}
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
mDialogMap.put(id, true);
}
#Override
public Object onRetainNonConfigurationInstance() {
if (mCurrentTask != null) {
mCurrentTask.detach();
if (mDialogMap.get((Integer) mCurrentTask.dialogId) != null
&& mDialogMap.get((Integer) mCurrentTask.dialogId)) {
return mCurrentTask;
}
}
return super.onRetainNonConfigurationInstance();
}
public void cleanupTask() {
if (mCurrentTask != null) {
mCurrentTask = null;
System.gc();
}
}
}
SuperAsyncTask.java
public abstract class SuperAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
protected BaseActivity mActivity = null;
protected Result mResult;
public int dialogId = -1;
protected abstract void onAfterExecute();
public SuperAsyncTask(BaseActivity activity, int dialogId) {
super();
this.dialogId = dialogId;
attach(activity);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mActivity.showDialog(dialogId); // go polymorphism!
}
protected void onPostExecute(Result result) {
super.onPostExecute(result);
mResult = result;
if (mActivity != null &&
mActivity.mDialogMap.get((Integer) dialogId) != null
&& mActivity.mDialogMap.get((Integer) dialogId)) {
postExecution();
}
};
public void attach(BaseActivity activity) {
this.mActivity = activity;
}
public void detach() {
this.mActivity = null;
}
public synchronized boolean postExecution() {
Boolean dialogExists = mActivity.mDialogMap.get((Integer) dialogId);
if (dialogExists != null || dialogExists) {
onAfterExecute();
cleanUp();
}
public boolean cleanUp() {
mActivity.removeDialog(dialogId);
mActivity.mDialogMap.remove((Integer) dialogId);
mActivity.cleanupTask();
detach();
return true;
}
}
Did someone from Google provide some "official solution"?
Yes.
The solution is more of an application architecture proposal rather that just some code.
They proposed 3 design patterns that allows an application to work in-sync with a server, regardless of the application state (it will work even if the user finishes the app, the user changes screen, the app gets terminated, every other possible state where a background data operation could be interrumpted, this covers it)
The proposal is explained in the Android REST client applications speech during Google I/O 2010 by Virgil Dobjanschi. It is 1 hour long, but it is extremely worth watching.
The basis of it is abstracting network operations to a Service that works independently to any Activity in the application. If you're working with databases, the use of ContentResolver and Cursor would give you an out-of-the-box Observer pattern that is convenient to update UI without any aditional logic, once you updated your local database with the fetched remote data. Any other after-operation code would be run via a callback passed to the Service (I use a ResultReceiver subclass for this).
Anyway, my explanation is actually pretty vague, you should definititely watch the speech.
While Mark's (CommonsWare) answer does indeed work for orientation changes, it fails if the Activity is destroyed directly (like in the case of a phone call).
You can handle the orientation changes AND the rare destroyed Activity events by using an Application object to reference your ASyncTask.
There's an excellent explanation of the problem and the solution here:
Credit goes completely to Ryan for figuring this one out.
After 4 years Google solved the problem just calling setRetainInstance(true) in Activity onCreate. It will preserve your activity instance during device rotation. I have also a simple solution for older Android.
you should call all activity actions using activity handler. So if you are in some thread you should create a Runnable and posted using Activitie's Handler. Otherwise your app will crash sometimes with fatal exception.
This is my solution: https://github.com/Gotchamoh/Android-AsyncTask-ProgressDialog
Basically the steps are:
I use onSaveInstanceState to save the task if it is still
processing.
In onCreate I get the task if it was saved.
In onPause I discard the ProgressDialog if it is shown.
In onResume I show the ProgressDialog if the task is still
processing.

Categories

Resources