get activity inside of static class - android

I have a class which extends Asynctask and I want to access my activity or context of it. Every time I try, I get cannot be referenced from a static context or Unable to add window -- token null is not for an application.
ps: I'm not using fragments, it's only activity.

You should be careful when passing context in an async task; you could create leaks. You can interact with your activity in an async task if you create a weak reference to it when you declare your task and acquire the reference when you need to use it by calling .get() on it.
private static class YourAsyncTask extends AsyncTask<String, String, String> {
Private WeakReference<YourActivity> weakReference;
YourAsyncTask(YourActivity context) {
weakReference = new WeakReference<>(context);
}
…
#Override
Protected void onPostExecute(String string) {
YourActivity activity = weakReference.get();
}
}

Related

GetHttpResponse Warning: This AsyncTask class should be static or leaks might occur [duplicate]

I am getting a warning in my code that states:
This AsyncTask class should be static or leaks might occur (anonymous android.os.AsyncTask)
The complete warning is:
This AsyncTask class should be static or leaks might occur (anonymous android.os.AsyncTask)
A static field will leak contexts. Non-static inner classes have an implicit reference to their outer class. If that outer class is for example a Fragment or Activity, then this reference means that the long-running handler/loader/task will hold a reference to the activity which prevents it from getting garbage collected. Similarly, direct field references to activities and fragments from these longer running instances can cause leaks. ViewModel classes should never point to Views or non-application Contexts.
This is my code:
new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... params) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
return null;
}
}.execute();
How do I correct this?
How to use a static inner AsyncTask class
To prevent leaks, you can make the inner class static. The problem with that, though, is that you no longer have access to the Activity's UI views or member variables. You can pass in a reference to the Context but then you run the same risk of a memory leak. (Android can't garbage collect the Activity after it closes if the AsyncTask class has a strong reference to it.) The solution is to make a weak reference to the Activity (or whatever Context you need).
public class MyActivity extends AppCompatActivity {
int mSomeMemberVariable = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// start the AsyncTask, passing the Activity context
// in to a custom constructor
new MyTask(this).execute();
}
private static class MyTask extends AsyncTask<Void, Void, String> {
private WeakReference<MyActivity> activityReference;
// only retain a weak reference to the activity
MyTask(MyActivity context) {
activityReference = new WeakReference<>(context);
}
#Override
protected String doInBackground(Void... params) {
// do some long running task...
return "task finished";
}
#Override
protected void onPostExecute(String result) {
// get a reference to the activity if it is still there
MyActivity activity = activityReference.get();
if (activity == null || activity.isFinishing()) return;
// modify the activity's UI
TextView textView = activity.findViewById(R.id.textview);
textView.setText(result);
// access Activity member variables
activity.mSomeMemberVariable = 321;
}
}
}
Notes
As far as I know, this type of memory leak danger has always been true, but I only started seeing the warning in Android Studio 3.0. A lot of the main AsyncTask tutorials out there still don't deal with it (see here, here, here, and here).
You would also follow a similar procedure if your AsyncTask were a top-level class. A static inner class is basically the same as a top-level class in Java.
If you don't need the Activity itself but still want the Context (for example, to display a Toast), you can pass in a reference to the app context. In this case the AsyncTask constructor would look like this:
private WeakReference<Application> appReference;
MyTask(Application context) {
appReference = new WeakReference<>(context);
}
There are some arguments out there for ignoring this warning and just using the non-static class. After all, the AsyncTask is intended to be very short lived (a couple seconds at the longest), and it will release its reference to the Activity when it finishes anyway. See this and this.
Excellent article: How to Leak a Context: Handlers & Inner Classes
Kotlin
In Kotlin just don't include the inner keyword for the inner class. This makes it static by default.
class MyActivity : AppCompatActivity() {
internal var mSomeMemberVariable = 123
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// start the AsyncTask, passing the Activity context
// in to a custom constructor
MyTask(this).execute()
}
private class MyTask
internal constructor(context: MyActivity) : AsyncTask<Void, Void, String>() {
private val activityReference: WeakReference<MyActivity> = WeakReference(context)
override fun doInBackground(vararg params: Void): String {
// do some long running task...
return "task finished"
}
override fun onPostExecute(result: String) {
// get a reference to the activity if it is still there
val activity = activityReference.get()
if (activity == null || activity.isFinishing) return
// modify the activity's UI
val textView = activity.findViewById(R.id.textview)
textView.setText(result)
// access Activity member variables
activity.mSomeMemberVariable = 321
}
}
}
Non-static inner classes holds a reference to the containing class. When you declare AsyncTask as an inner class, it might live longer than the containing Activity class. This is because of the implicit reference to the containing class. This will prevent the activity from being garbage collected, hence the memory leak.
To solve your problem, either use static nested class instead of anonymous, local, and inner class or use top-level class.
This AsyncTask class should be static or leaks might occur because
When Activity is destroyed, AsyncTask (both static or non-static) still running
If inner class is non-static (AsyncTask) class, it will have reference to the outer class (Activity).
If a object has no references point to it, Garbage Collected will release it. If a object is unused and Garbage Collected can not release it => leak memory
=> If AsyncTask is non-static, Activity won't release event it is destroyed => leak
Solution for update UI after make AsyncTask as static class without leak
1) Use WeakReference like #Suragch answer
2) Send and remove Activity reference to (from) AsyncTask
public class NoLeakAsyncTaskActivity extends AppCompatActivity {
private ExampleAsyncTask asyncTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// START AsyncTask
asyncTask = new ExampleAsyncTask();
asyncTask.setListener(new ExampleAsyncTask.ExampleAsyncTaskListener() {
#Override
public void onExampleAsyncTaskFinished(Integer value) {
// update UI in Activity here
}
});
asyncTask.execute();
}
#Override
protected void onDestroy() {
asyncTask.setListener(null); // PREVENT LEAK AFTER ACTIVITY DESTROYED
super.onDestroy();
}
static class ExampleAsyncTask extends AsyncTask<Void, Void, Integer> {
private ExampleAsyncTaskListener listener;
#Override
protected Integer doInBackground(Void... voids) {
...
return null;
}
#Override
protected void onPostExecute(Integer value) {
super.onPostExecute(value);
if (listener != null) {
listener.onExampleAsyncTaskFinished(value);
}
}
public void setListener(ExampleAsyncTaskListener listener) {
this.listener = listener;
}
public interface ExampleAsyncTaskListener {
void onExampleAsyncTaskFinished(Integer value);
}
}
}

Warning: This AsyncTask class should be static or leaks might occur

I am getting a warning in my code that states:
This AsyncTask class should be static or leaks might occur (anonymous android.os.AsyncTask)
The complete warning is:
This AsyncTask class should be static or leaks might occur (anonymous android.os.AsyncTask)
A static field will leak contexts. Non-static inner classes have an implicit reference to their outer class. If that outer class is for example a Fragment or Activity, then this reference means that the long-running handler/loader/task will hold a reference to the activity which prevents it from getting garbage collected. Similarly, direct field references to activities and fragments from these longer running instances can cause leaks. ViewModel classes should never point to Views or non-application Contexts.
This is my code:
new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... params) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
return null;
}
}.execute();
How do I correct this?
How to use a static inner AsyncTask class
To prevent leaks, you can make the inner class static. The problem with that, though, is that you no longer have access to the Activity's UI views or member variables. You can pass in a reference to the Context but then you run the same risk of a memory leak. (Android can't garbage collect the Activity after it closes if the AsyncTask class has a strong reference to it.) The solution is to make a weak reference to the Activity (or whatever Context you need).
public class MyActivity extends AppCompatActivity {
int mSomeMemberVariable = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// start the AsyncTask, passing the Activity context
// in to a custom constructor
new MyTask(this).execute();
}
private static class MyTask extends AsyncTask<Void, Void, String> {
private WeakReference<MyActivity> activityReference;
// only retain a weak reference to the activity
MyTask(MyActivity context) {
activityReference = new WeakReference<>(context);
}
#Override
protected String doInBackground(Void... params) {
// do some long running task...
return "task finished";
}
#Override
protected void onPostExecute(String result) {
// get a reference to the activity if it is still there
MyActivity activity = activityReference.get();
if (activity == null || activity.isFinishing()) return;
// modify the activity's UI
TextView textView = activity.findViewById(R.id.textview);
textView.setText(result);
// access Activity member variables
activity.mSomeMemberVariable = 321;
}
}
}
Notes
As far as I know, this type of memory leak danger has always been true, but I only started seeing the warning in Android Studio 3.0. A lot of the main AsyncTask tutorials out there still don't deal with it (see here, here, here, and here).
You would also follow a similar procedure if your AsyncTask were a top-level class. A static inner class is basically the same as a top-level class in Java.
If you don't need the Activity itself but still want the Context (for example, to display a Toast), you can pass in a reference to the app context. In this case the AsyncTask constructor would look like this:
private WeakReference<Application> appReference;
MyTask(Application context) {
appReference = new WeakReference<>(context);
}
There are some arguments out there for ignoring this warning and just using the non-static class. After all, the AsyncTask is intended to be very short lived (a couple seconds at the longest), and it will release its reference to the Activity when it finishes anyway. See this and this.
Excellent article: How to Leak a Context: Handlers & Inner Classes
Kotlin
In Kotlin just don't include the inner keyword for the inner class. This makes it static by default.
class MyActivity : AppCompatActivity() {
internal var mSomeMemberVariable = 123
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// start the AsyncTask, passing the Activity context
// in to a custom constructor
MyTask(this).execute()
}
private class MyTask
internal constructor(context: MyActivity) : AsyncTask<Void, Void, String>() {
private val activityReference: WeakReference<MyActivity> = WeakReference(context)
override fun doInBackground(vararg params: Void): String {
// do some long running task...
return "task finished"
}
override fun onPostExecute(result: String) {
// get a reference to the activity if it is still there
val activity = activityReference.get()
if (activity == null || activity.isFinishing) return
// modify the activity's UI
val textView = activity.findViewById(R.id.textview)
textView.setText(result)
// access Activity member variables
activity.mSomeMemberVariable = 321
}
}
}
Non-static inner classes holds a reference to the containing class. When you declare AsyncTask as an inner class, it might live longer than the containing Activity class. This is because of the implicit reference to the containing class. This will prevent the activity from being garbage collected, hence the memory leak.
To solve your problem, either use static nested class instead of anonymous, local, and inner class or use top-level class.
This AsyncTask class should be static or leaks might occur because
When Activity is destroyed, AsyncTask (both static or non-static) still running
If inner class is non-static (AsyncTask) class, it will have reference to the outer class (Activity).
If a object has no references point to it, Garbage Collected will release it. If a object is unused and Garbage Collected can not release it => leak memory
=> If AsyncTask is non-static, Activity won't release event it is destroyed => leak
Solution for update UI after make AsyncTask as static class without leak
1) Use WeakReference like #Suragch answer
2) Send and remove Activity reference to (from) AsyncTask
public class NoLeakAsyncTaskActivity extends AppCompatActivity {
private ExampleAsyncTask asyncTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// START AsyncTask
asyncTask = new ExampleAsyncTask();
asyncTask.setListener(new ExampleAsyncTask.ExampleAsyncTaskListener() {
#Override
public void onExampleAsyncTaskFinished(Integer value) {
// update UI in Activity here
}
});
asyncTask.execute();
}
#Override
protected void onDestroy() {
asyncTask.setListener(null); // PREVENT LEAK AFTER ACTIVITY DESTROYED
super.onDestroy();
}
static class ExampleAsyncTask extends AsyncTask<Void, Void, Integer> {
private ExampleAsyncTaskListener listener;
#Override
protected Integer doInBackground(Void... voids) {
...
return null;
}
#Override
protected void onPostExecute(Integer value) {
super.onPostExecute(value);
if (listener != null) {
listener.onExampleAsyncTaskFinished(value);
}
}
public void setListener(ExampleAsyncTaskListener listener) {
this.listener = listener;
}
public interface ExampleAsyncTaskListener {
void onExampleAsyncTaskFinished(Integer value);
}
}
}

Substitute for activity argument when calling a class from AsyncTask

here's a portion of my code:
public class Login extends Activity {
private class LoginUser extends AsyncTask<String, String, Boolean> {
#Override
protected void onPostExecute(Boolean returnResult) {
DialogSelectAccount dsa=new DialogSelectAccount(getParent());
dsa.show();
}
}
}
public class DialogSelectAccount extends Dialog implements android.view.View.OnClickListener {
public DialogSelectAccount(Activity a) {
super(a);
}
}
but when I run the app, it get a NPE error at the "super(a)" under the public DialogSelectAccount();
but when I changed my code to
public class Login extends Activity {
private class LoginUser extends AsyncTask<String, String, Boolean> {
#Override
protected void onPostExecute(Boolean returnResult) {
test();
}
}
public void test(){
DialogSelectAccount dsa=new DialogSelectAccount(this);
dsa.show();
}
}
it works. So what if I don't want to create a separate method like above and calls DialogSelectAccount directly inside the onPostExecute, what should I pass as the argument?
Thanks
So what if I don't want to create a separate method like above and calls DialogSelectAccount directly inside the onPostExecute, what should I pass as the argument?
answer:
DialogSelectAccount dsa=new DialogSelectAccount(Login.this);
This is rather general java question, for more on inner classes read here: Getting hold of the outer class object from the inner class object
The dialog class needs a Context attribute.
When you say getParent() - I suppose it does not return context.
You can keep the context attribute in a global class and retrieve it - though I will not recommend that.

Using delegates for AsyncTask

I'm having trouble implementing a delegate in my android app.
In my GetData class I have nested asynctask, and I need to notify my main activity when all the work has actually finished.
I came up with this answer from Mohd Mufiz
What is the best way for AsyncTask to notify parent Activity about completion?
But I always get stuck at the same point:
in my GetData class I call a constructor with the delegate as only argument:
public class GetData {
private TaskDelegate delegate;
public GetData(TaskDelegate delegate) {
this.delegate = delegate;
}
...
}
In my main activity I don't know what I have to pass to get it working:
GetData getData = new GetData(**???**);
Going from the question you linked to, that defined TaskDelegate as :
public interface TaskDelegate {
public void taskCompletionResult(String result);
}
You can pass GetData any instance of a class that implements TaskDelegate - but typically, that would be the object that creates it - ie. your main activity (and so, therefore, it would also implement "void taskCompletionResult(String result);"). That then means you can pass "this" to GetData's constructor, so :
public class MyMainActivity implements TaskDelegate {
public void someMethod() {
GetData getData = new GetData(this);
}
public void taskCompletionResult(String result) {
// do stuff
}
}

How to call Activity method in an AsyncTask

I would like to call an Activity method after the onPostExecute of my AsyncTask.
Do you know how I can do that?
I want to call in the sendSMS(String phoneNumber, String message) method in the onPostExecute.
One way is to pass an instance of the Activity through PostTask constructor, something like:
private class PostTask extends AsyncTask<String, Integer, String>
{
private AsyncBigCalculActivity activity;
public PostTask(AsyncBigCalculActivity activity)
{
this.activity = activity;
}
// ...
}
and on creating the PostTask instance, pass the activity instance:
new PostTask(this).execute();
Now you can invoke sendSMS() from within PostTask, like:
activty.sendSMS(...);
Also note that if you are defining the PostTask as a private class inside the activty, then you can invoke sendSMS() like:
AsyncBigCalculActivity.this.sendSMS(...);
Add a constructor and a global variable to your AsyncTask like this:
AsyncBigCalculActivity mActivity;
public PostTask(AsyncBigCalculActivity a) {
mActivity = a;
}
Then simply use mActivity.sendSMS("test", "test") when you need it.
However, you should really have methods like sendSMS() in a utility class.
If your AsyncTask is an inner class of your Activity then you should be able to call the Activity method from your onPostExecute(). Otherwise, you can send the Context to a constructor of your AsyncTask and uses that to call the method
Write a Callback
You can create a CallBack using an interface. This way you can use your AsyncTask with any activity. (Loosely coupled code)
1) Create a Callback
interface MyAsyncTaskCallBack{
public void doStuff(String arg1,String arg2);
}
2) Initialize the callback in your AsyncTask
private class MyTask extends AsyncTask<String, Void, Void>
{
private MyAsyncTaskCallBackactivity callback;
public MyTask(MyAsyncTaskCallBackactivity callback)
{
this.callback = callback;
}
//Call callback.doStuff(....phonenum, ....message); in your postExecute
}
3) Implement the Callback in your Activity and override doStuff() method
public YourActivity extends AppCompatActivity implements MyAsyncTaskCallBack{
// Your Activity code
// new MyTask(this).execute("phonenum","msg"); //<--- This is how you run AsyncTask
private void sendMessage(String num, String msg){
// send msg logic
}
#Override
public void doStuff(String arg1,String arg2){
sendMessage(arg1,arg2); // invoke activity method
}
}

Categories

Resources