Issue
i'm working on a project and i have a question about the AsyncTask. What i'm trying to do is to separate the AsyncTask from my classes, by writing it once and call it from any class. So I have created a class named A that is a fragment activity and contains a list view. In this class i'm creating an object of the AsyncTask to get data from the xml and create a list with this data. When the AsyncTask finished i want to send this list back to the class A and continue the process by adding the list in the list view and update the layout. What i have to do in the onPostExecute to past the data in the class A and how i can make the class to know about the process of the AsyncTask so it can continue? Thanks
Here is a simple of my code in which i'm creating the object of the AsyncTask.
GetXMLData load = new GetXMLData();
if (this.count == 1)
{
load.Set_URL(XML_URL);
this.count++;
}
else
{
load.Set_URL(XML_URL, "?paged=" + this.count);
this.count++;
}
LinkedList<Contents> content_list;
load.start_LoadContents();
this.list = new ArrayList<Contents>();
content_list = load.get_XML_List();
Log.i("content_list", "The content_list is " + content_list.size());
Solution
You can try this
public class MainActivity extends Activity implements TaskListener {
TaskListener listener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = this;
new BackgroundTask(listener).execute("");
}
@Override
public void taskComplete(ArrayList<String> list) {
if (list.size() != 0) {
Log.i("Log", "list " + list.get(0));
}
}
}
TaskListener.java
public interface TaskListener {
public void taskComplete(ArrayList<String> list);
}
BackgroundTask.java
public class BackgroundTask extends AsyncTask<String, String, String> {
TaskListener listner;
ArrayList<String> list = new ArrayList<String>();
public BackgroundTask(TaskListener l) {
this.listner = l;
}
@Override
protected String doInBackground(String... params) {
// do your background task like below
list.add("Android");
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
listner.taskComplete(list);
}
}
Answered By - Sonali8890
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.