Reputation: 3534
I am a newbie in Android development. Now I am trying to parse. I have got many tutorials for parsing XML. But I would like to know parse XML asynchronously. I have found somewhere, xml can be loaded asynchronously using AsyncTask. Can anybody help me to find it out.
Thanks in advance
Upvotes: 0
Views: 3955
Reputation: 6205
public class _StackOverflowActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String yourXmlString = "<put your xml String here>";
ParseXMLTask parseXMLTask = new ParseXMLTask();
parseXMLTask.execute(yourXmlString);
}
class ParseXMLTask extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
String yourXml = params[0];
//Parse your xml here
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//do something after parsing is done
}
}
}
First, you have to extend the class AsyncTask. In my example I named it ParseXMLTask.
AsyncTask requires you to implement one method which is "doInBackground". doInBackground runs in a separate thread, put your code for parsing the xml there.
After the thread finishes, onPostExecute is called. onPostExecute runs in your main thread, you can use this if you wish to perform something after doInBackground finishes
To use ParseXMLTask, you have to instantiate it to an object. Then run the command .execute()
. You can pass objects in execute
similar to what I have done parseXMLTask.execute(yourXmlString);
. You can pass as many variables as you like and be sure to handle them in doInBackground
similar to String yourXml = params[0];
. If you have a second variable passed in .execute say... parseXml.execute(yourXmlString, my2ndVariable);
, handle it in doInBackground through
String yourXml = params[0];
String the2ndVariable = params[1];
When you call .execute you tell AsyncTask to run whatever code you have placed in doInBackground in a separate thread.
Upvotes: 1
Reputation: 2425
Here's a tutorial for using AsyncTask:
And one for parsing RSS / XML:
You need to call your parse function in doInBackground in the AsyncTask.
Upvotes: 3