I have an Async Task, where I had a warning that it should be static or leaks might occur.
So I used a WeakReference like this:
private static class GetContacts extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
private WeakReference<Novinky> activityReference;
GetContacts(Novinky context) {
activityReference = new WeakReference<>(context);
}
#Override
protected void onPreExecute() {
// get a reference to the activity if it is still there
Novinky activity = activityReference.get();
if (activity == null || activity.isFinishing()) return;
super.onPreExecute();
dialog = new ProgressDialog(activity);
dialog.setMessage("Načítavam");
dialog.setTitle("Pripájam sa k serveru");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... args) {
HttpHandler sh = new HttpHandler();
String url = "https://www...";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray actors = jsonObj.getJSONArray("result");
for (int i = 0; i < actors.length(); i++) {
JSONObject c = actors.getJSONObject(i);
Actors actor = new Actors();
actor.setLetter(c.getString("letter"));
actor.setNazov(c.getString("name"));
actor.setPerex(c.getString("perex"));
actorsList.add(actor);
}
} catch (final JSONException e) {
Novinky.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(Novinky.this.getApplicationContext(),
"Chyba dát: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}); }
return true;
} else {
Novinky.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(Novinky.this.getApplicationContext(),
"Chyba internetového pripojenia.",
Toast.LENGTH_LONG).show();
}
});
return false;
}
}
protected void onPostExecute(Boolean result) {
// get a reference to the activity if it is still there
Novinky activity = activityReference.get();
if (activity == null || activity.isFinishing()) return;
super.onPostExecute(result);
dialog.dismiss();
adapter.notifyDataSetChanged();
}
}
Now that warning is gone, but I am still fighting with some other errors which came up due my changes.
1/ actorsList.add(actor); - in my for loop now says Non-static field 'actorsList' cannot be referenced from a static context
2/ in catch and else statement where runOnUiThread is placed I have issues with Novinky.this.runOnUiThread - cannot be referenced from a static context
If I simply replace Novinky.this with the WeakReference (activityReference) then it says class name is expected, so not sure how to correctly replace Novinky.this in those threads.
I tried also to use Novinky activity = activityReference.get(); and then use activity.runOnUiThread - this removes the error, but the definition of Novinky activity = activityReference.get(); has then warning This field leaks a context object
3/ The last issue is in my onPostExecute - adapter.notifyDataSetChanged();. The error says: Non-static field 'adapter' cannot be referenced from a static context
UPDATE: I solved it somehow and now I have no errors and the app is running, however still not sure if I solved it correctly:
For 1/ I defined static ArrayList<Actors> actorsList; in the main class.
2/ in catch and else I defined
final Novinky activity = activityReference.get();
and then:
activity.runOnUiThread
3/ in onPostExecute I used activity.adapter.notifyDataSetChanged();
You should be able to access your instance of the list the same way you access the adapter:
activityReference.get().actorsList
Related
I want to use WeakReference to avoid a memory leak in AsyncTask. The examples I find online only use the get() method in onPostExecute, but I also want to use it to update the progress. Now I wonder if that very frequent call of the get method can in itself cause a memory leak?
private static class ExampleAsyncTask extends AsyncTask<Integer, Integer, String> {
private WeakReference<MainActivity> activityReference;
ExampleAsyncTask(MainActivity context) {
activityReference = new WeakReference<>(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
MainActivity activity = activityReference.get();
if (activityReference.get() == null) {
return;
}
activity.progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(Integer... integers) {
Log.i("TAG", "doInBackground started");
for (int i = 1; i < integers[0]; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress((i * 100) / integers[0]);
}
return "Finished";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
MainActivity activity = activityReference.get();
if (activity == null || activity.isFinishing()) {
return;
}
activity.progressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
MainActivity activity = activityReference.get();
if (activity == null || activity.isFinishing()) {
return;
}
activity.progressBar.setProgress(0);
activity.progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
}
}
Your code almost has no strong reference as far as the get and onProgressUpdate are concerned because you are using local variable which will go out of scope, the moment onProgressUpdate is finished.
So basically everytime your code is accessing the reference, retrieved from get() method so it is safe. Although it would have been an issue, if you would have kept a reference, declared outside onProgressUpdate method
when i run my code, it returns a value as "null"`
private class MessageActivityLoaderTask extends AsyncTask<Void, Void, Contentlist> {
private LinkedMultiValueMap<String, String> formData;
Activity activity;
public MessageActivityLoaderTask(Activity activity) {
this.activity = activity;
}
#Override
protected void onPreExecute() {
formData = new LinkedMultiValueMap<String, String>();
mProgress.setMessage("Please wait..");
mProgress.show();
}
#Override
protected Contentlist doInBackground(Void... params) {
String url = getString(R.string.base_url) + "/example/example1/1";
Contentlist mess = null;
try {
mess = RestUtils.exchangeFormData(url, HttpMethod.GET, formData, Contentlist.class);
} catch (Exception e) {
e.printStackTrace();
mProgress.dismiss();
}
return mess;
}
protected void onPostExecute(Contentlist result) {
if (result== null) {
Toast message = Toast.makeText(ListobjectsActivity.this, "result is empty", Toast.LENGTH_SHORT);
message.show();
} else {
ListactivityAdapter adapter = new ListactivityAdapter(this.activity, result.getContents());
ListView list = (ListView) activity.findViewById(R.id.account);
list.setAdapter(adapter);
mProgress.dismiss();
}
}`
Your AsyncTask looks like it is set up correctly, so onPostExecute() will receive the ContentList returned by doInBackgroun(). Since onPostExecute() is seeing a null, then doInBackground() is returning a null. That means that either doInBackground() is getting an exception and mess is never set to a non-null value by falling through the catch or RestUtils.exchangeFormData() is returning a null.
I suggest that you debug the code in this area to see what is really going on. It is not likely to be an AsyncTask problem.
I got a weird problem with an android activity : I re-used one of my previous activity that works well, but this time all I got is "Can't create handler inside thread that has not called Looper.prepare()"
I tried to debug, and everything in the async task is performing well but when I reach then end of onPostExecute() the error is raised.
So I tried to disable my process about the process dialog, the only change is that it's crashing on line upper.
Here is the code :
public class DateActivity extends ActionBarActivity{
ProgressDialog mProgressDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date);
ActionBar actionBar = this.getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(getResources().getString(R.string.actionbar_titre_date));
if (VerifConnexion.isOnline(this)) {
this.mProgressDialog = ProgressDialog.show(this, getResources().getString(R.string.loading),
getResources().getString(R.string.loading), true);
new QueryForDateTask().execute(this.mProgressDialog, this, this.getApplicationContext());
} else {
...
}
});
alertDialog.show();
}
}
private class QueryForDateTask extends
AsyncTask<Object, Void, ArrayList<String>> {
private ProgressDialog mProgressDialog;
private Activity act;
private Context context;
protected ArrayList<String> doInBackground(Object... o) {
this.mProgressDialog = (ProgressDialog) o[0];
this.act = (Activity) o[1];
this.context = (Context) o[2];
ArrayList<String> listeDate = this.parseJSON(this.startQuerying());
return listeDate;
}
public JSONObject startQuerying() {
JSONRequest jr = new JSONRequest();
String from = getResources().getString(R.string.api_param_from);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.FRANCE);
from += "=" + sdf.format(new Date());
String url = getResources().getString(
R.string.api_dates_json);
JSONObject jo = jr.getJSONFromUrl(url + "?" + from);
return jo;
}
public ArrayList<String> parseJSON(JSONObject jsonObject) {
ArrayList<String> l = new ArrayList<String>();
try {
JSONArray array = jsonObject.getJSONArray("dates");
if (array != null) {
for (int i = 0; i < array.length(); i++) {
String type = array.getString(i);
l.add(type);
} // fin parcours JSONArray
}
} catch (Exception _e) {
}
return l;
}
protected void onProgressUpdate(Integer... progress) {
// setProgressPercent(progress[0]);
}
protected void onPostExecute(ArrayList<String> lDate) {
// Create items for the ListView
DateAdapter adapter = new DateAdapter(this.context, R.layout.searchitem_date, lDate, this.act);
// specify the list adaptor
((ListView)findViewById(R.id.list)).setAdapter(adapter);
this.mProgressDialog.dismiss();
}
} // fin async
}
I tried this to replace the call to the AsyncTask :
runOnUiThread(new Runnable() {
public void run() {
QueryForDateTask task = new QueryForDateTask();
task.execute(DateActivity.this.mProgressDialog, DateActivity.this, DateActivity.this.getApplicationContext());
}
});
(like explained in Asynctask causes exception 'Can't create handler inside thread that has not called Looper.prepare()' as far as I understood), but the result is exactly the same.
So I can't understand why it is not working in this activity despite all is ok for the other ones of the project.
Any clue ?
Thank a lot for all ideas :)
Just a post to mark the trouble as resolved :
the adapter i used was buggy in parsing parameters and throwed a NullPointerException.
I just fixed it, the AsyncTask is now running without problem.
I need to pass the async task result to the calling class. I have created a separate ASync class which is called from other classes. I am passing the response from Async task in "Post Execute" method to calling class method but getting null point exception. Below is my calling method in
public boolean getCategories() {
serUri = "categories.json";
WebServiceAsyncTask webServiceTask = new WebServiceAsyncTask();
webServiceTask.execute(serUri,this);
return true;
}
The method to be executed with result from below aysnc task is
public void writeJSONArray(final JSONArray result)
{
try {
for (int i=0; i<result.length();i++){
JSONObject c = result.getJSONObject(i);
String name = c.getString("catname");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
WebServiceAsyncTask Class:
public class WebServiceAsyncTask extends AsyncTask<Object,Void,JSONArray> {
ROMSjson roms;
private static JSONArray json = null;
private Context context = null;
protected JSONArray doInBackground(Object... params) {
// TODO Auto-generated method stub
String serviceUrl = (String) params[0];
final HTTPHelper httph = new HTTPHelper(serviceUrl,context);
if(serviceUrl.equalsIgnoreCase("categories.json")) {
json = httph.fetch();
}else if(serviceUrl.equalsIgnoreCase("categories/create"))
{
}
return json;
}
#Override
protected void onPostExecute(JSONArray result) { // invoked on the ui thread
roms.writeJSONArray(result);
super.onPostExecute(result);
}
I am getting null point exception when roms.writeJSONArray(result) is called. The result is correctly received before this command. I checked with Log statement. Also if I write the writeJSONArray method in my Async class instead of calling class, all works fine.
I am not sure if I am missing something in passing the result or while calling methods. Please advise. Thanks.
null pointer exception
because roms is null
you are declaring ROMSjson roms; inside WebServiceAsyncTask but not initializing it !
and using it inside `onPostExecute(JSONArray result)
roms.writeJSONArray(result);` // here roms in null
so initialize roms before using it !
Here is the problem:
else if(serviceUrl.equalsIgnoreCase("categories/create"))
{
// if it falls to this condition then your json object appears to be null
}
Hope this helps.
Interface is the best way for passing data between classes.
create a public interface
public interface WebCallListener{
void onCallComplete(JSONArray result);
}
what to do in your class?
public class WebServiceAsyncTask extends AsyncTask<Object,Void,JSONArray> {
ROMSjson roms;
private static JSONArray json = null;
private Context context = null;
//update
private WebCallListener local;
public WebServiceAsyncTask(WebCallListener listener){
local=listener;
}
/////
protected JSONArray doInBackground(Object... params) {
// TODO Auto-generated method stub
String serviceUrl = (String) params[0];
final HTTPHelper httph = new HTTPHelper(serviceUrl,context);
if(serviceUrl.equalsIgnoreCase("categories.json")) {
json = httph.fetch();
}else if(serviceUrl.equalsIgnoreCase("categories/create"))
{
}
return json;
}
#Override
protected void onPostExecute(JSONArray result) { // invoked on the ui thread
//update
super.onPostExecute(result);
local.onCallComplete(result);
}
From Your Calling class.
public class CallingClass extends Activity{
protecte void oncreate(Bundle b){
new WebServiceAsyncTask(new WebCallListener() {
#Override
public void onCallComplete(JSONArray result) {
//play with your response
}
});
}
}
I have an application that does some long calculations, and I would like to show a progress dialog while this is done. So far I have found that I could do this with threads/handlers, but didn't work, and then I found out about the AsyncTask.
In my application I use maps with markers on it, and I have implemented the onTap function to call a method that I have defined. The method creates a dialog with Yes/No buttons, and I would like to call an AsyncTask if Yes is clicked. My question is how to pass an ArrayList<String> to the AsyncTask (and work with it there), and how to get back a new ArrayList<String> like a result from the AsyncTask?
The code of the method looks like this:
String curloc = current.toString();
String itemdesc = item.mDescription;
ArrayList<String> passing = new ArrayList<String>();
passing.add(itemdesc);
passing.add(curloc);
ArrayList<String> result = new ArrayList<String>();
new calc_stanica().execute(passing,result);
String minim = result.get(0);
int min = Integer.parseInt(minim);
String glons = result.get(1);
String glats = result.get(2);
double glon = Double.parseDouble(glons);
double glat = Double.parseDouble(glats);
GeoPoint g = new GeoPoint(glon, glat);
String korisni_linii = result.get(3);
So, as you see, I would like to send the string array list "passing" to the AsyncTask, and to get the "result" string array list back from it. And the calc_stanica AssycTask class looks like this:
public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(baraj_mapa.this);
dialog.setTitle("Calculating...");
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.show();
}
protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
//Some calculations...
return something; //???
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
So my question is how to get the elements of the "passing" array list in the AsyncTask doInBackground method (and use them there), and how to return an array list to use in the main method (the "result" array list)?
Change your method to look like this:
String curloc = current.toString();
String itemdesc = item.mDescription;
ArrayList<String> passing = new ArrayList<String>();
passing.add(itemdesc);
passing.add(curloc);
new calc_stanica().execute(passing); //no need to pass in result list
And change your async task implementation
public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(baraj_mapa.this);
dialog.setTitle("Calculating...");
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.show();
}
protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
ArrayList<String> result = new ArrayList<String>();
ArrayList<String> passed = passing[0]; //get passed arraylist
//Some calculations...
return result; //return result
}
protected void onPostExecute(ArrayList<String> result) {
dialog.dismiss();
String minim = result.get(0);
int min = Integer.parseInt(minim);
String glons = result.get(1);
String glats = result.get(2);
double glon = Double.parseDouble(glons);
double glat = Double.parseDouble(glats);
GeoPoint g = new GeoPoint(glon, glat);
String korisni_linii = result.get(3);
}
UPD:
If you want to have access to the task starting context, the easiest way would be to override onPostExecute in place:
new calc_stanica() {
protected void onPostExecute(ArrayList<String> result) {
// here you have access to the context in which execute was called in first place.
// You'll have to mark all the local variables final though..
}
}.execute(passing);
Why would you pass an ArrayList??
It should be possible to just call execute with the params directly:
String curloc = current.toString();
String itemdesc = item.mDescription;
new calc_stanica().execute(itemdesc, curloc)
That how varrargs work, right?
Making an ArrayList to pass the variable is double work.
I sort of agree with leander on this one.
call:
new calc_stanica().execute(stringList.toArray(new String[stringList.size()]));
task:
public class calc_stanica extends AsyncTask<String, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(String... args) {
...
}
#Override
protected void onPostExecute(ArrayList<String> result) {
... //do something with the result list here
}
}
Or you could just make the result list a class parameter and replace the ArrayList with a boolean (success/failure);
public class calc_stanica extends AsyncTask<String, Void, Boolean> {
private List<String> resultList;
#Override
protected boolean doInBackground(String... args) {
...
}
#Override
protected void onPostExecute(boolean success) {
... //if successfull, do something with the result list here
}
}
I dont do it like this. I find it easier to overload the constructor of the asychtask class ..
public class calc_stanica extends AsyncTask>
String String mWhateveryouwantToPass;
public calc_stanica( String whateveryouwantToPass)
{
this.String mWhateveryouwantToPass = String whateveryouwantToPass;
}
/*Now you can use whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/ ... ...
You can receive returning results like that:
AsyncTask class
#Override
protected Boolean doInBackground(Void... params) {
if (host.isEmpty() || dbName.isEmpty() || user.isEmpty() || pass.isEmpty() || port.isEmpty()) {
try {
throw new SQLException("Database credentials missing");
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
this.conn = DriverManager.getConnection(this.host + ':' + this.port + '/' + this.dbName, this.user, this.pass);
} catch (SQLException e) {
e.printStackTrace();
}
return true;
}
receiving class:
_store.execute();
boolean result =_store.get();
Hoping it will help.