Skip to content Skip to sidebar Skip to footer

Having Trouble With Async Task And Flow Of Program

I am currently designing an app that lets users read news articles and its necessary to get information from the internet in order to populate a list and display it to the user. I'

Solution 1:

There is one simple solution to overcome and return your data in any class / activity / fragment.

You have write a custom listener in asynctask class (GetArticlesFromRSS in your case) and call listener in onPostExecute method.

example of listener

    public interface OnAsyncResult {  
        public abstract void onResultSuccess(ArrayList<Article> result);  
        public abstract void onResultFail(int resultCode, String errorMessage);  
   }

create object on OnAsyncResult in your "GetArticlesFromRSS.java" lets say

OnAsyncResult onAsyncResult = null;

setOnAsyncResult(OnAsyncResult callBack)
{
  this.onAsyncResult = callback;
}

then in your post execute method you can use this listener as below

@Override
protected void onPostExecute(ArrayList<Article> result)
{
    dialog.dismiss();
    articlesReturned = result;


    if (MainActivity.articlesReturned.size() > 0){
        if(onAsyncResult!=null)
            onAsyncResult.onResultSuccess(result);

        Toast.makeText(getApplicationContext(), "Ok", Toast.LENGTH_LONG).show();
    }
    else{
        if(onAsyncResult!=null)
            onAsyncResult.onResultFail(1, "Error, Check Network Connection.");

        Toast.makeText(getApplicationContext(), "Error, Check Network Connection.", Toast.LENGTH_LONG).show();
    }

}

This will solve your purpose.


Solution 2:

I think it'd be better to use a service in this case. When the UI needs update can bind the service and get the information.


Solution 3:

There is no need to make the UI thread wait...

The postExecute runs on the UI thread, so you can set your ui elements from that method. You should define how to set them in your Acivity / Fragments, and then have the post execute call these methods with the information to update the UI.

Also, inflating a view takes like fractions of a second. You can launch the async tasks after inflation to be sure the UI elements are there. Or you could do something more complicated like caching the result if you NEED to launch the async before inflation (and its possible for it to return before the app is done).


Post a Comment for "Having Trouble With Async Task And Flow Of Program"