Issue
I have the following static AsyncTask
class:
public static class MyAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(String... params) {
//Do heavy stuff
}
@Override
protected void onPostExecute(String string) {
super.onPostExecute(string);
progressBar.setVisibility(View.GONE);
}
}
I want to show/hide the progressBar
as you see in those two methods. The problem is that I have to make the progressBar
static. Doing this, I get:
Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)
If I remove the static that stays in front of my MyAsyncTask
class I get:
This AsyncTask class should be static or leaks might occur (MainActivity.MyAsyncTask)
How to solve this?
Edit:
private void checkUser() {
uidRef.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
User user = document.toObject(User.class);
if (user == null) {
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute(url);
}
}
});
}
Solution
I faced this "static" problem in async task earlier and there is a really nice way to get the output of async task back to activity . Simply put
String output = myAsyncTask.execute(url).get();
You will get the output, The final code is.
progressBar.setVisibility(View.VISIBLE);
String output = myAsyncTask.execute(url).get();
progressBar.setVisibility(View.GONE);
Until you get the output the next line will not be executed. I am adding an example code for further demo.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button exe = findViewById(R.id.async);
exe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
updateAsyncTask up = new updateAsyncTask();
long l = up.execute().get();
System.out.println("inside main "+l);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
private static class updateAsyncTask extends AsyncTask<Void, Void, Long> {
@Override
protected Long doInBackground(Void... voids) {
long l = 0;
for(int i=0;i<2000;i++)
{
l = l+i;
System.out.println(l);
}
return l;
}
}
Answered By - amitava
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.