Android: How to store value in main activity's variable?
I want to store some values on a main activity's variable after parsing an xml file from the net, I have the following codes, it runs but then it force closes:
private class parseXMLAsync extends AsyncTask <String, String, String>{
protected void onPreExecute(){
super.onPreExecute();
showDialog(PARSE_XML);
}
@Override
protected String doInBackground(String... strings) {
try{
Engagia.this.url.openConnection();
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
ExampleHandler myExampleHandler = new ExampleHandler();
xr.setContentHandler(myExampleHandler);
xr.parse(new InputSource(Engagia.this.url.openStream()));
List<ParsedExampleDataSet> parsedExampleDataSet = myExampleHandler.getParsedData();
Iterator i;
i = parsedExampleDataSet.iterator();
ParsedExampleDataSet dataItem;
开发者_运维问答 while(i.hasNext()){
dataItem = (ParsedExampleDataSet) i.next();
String folder = dataItem.getParentTag();
if( folder == "Videos" ){
MainAct.this.videoNames[MainAct.this.videoCount] = dataItem.getName();
MainAct.this.videoCount++;
}
}
}catch(Exception e){
Log.e(LOG_TAG, e.toString());
}
return null;
}
@Override
protected void onPostExecute(String lenghtOfFile) {
try{
if( mProgressDialog.isShowing() ){
dismissDialog(PARSE_XML);
}
//String str_contents = null;
/*
for(String str : MainAct.this.videoNames ){
str_contents = str_contents + str + "\n";
}
*/
}catch(Exception e){
Log.e(LOG_TAG, e.toString());
}
PopIt("Parsing Done", "STR CONTENTS >> " + Engagia.this.videoNames[0], "Denied");
}
}
The logcat says:
To Store value in MainAct activity
First make sure MainAct activity is not finished while you are using Async task. because you want to store the values as instance variable of MainAct
Avoid assigning values like following
MainAct.this.videoNames[MainAct.this.videoCount] = dataItem.getName();
Better create a method in MainAct which will set value of videoNames
there. But call that method in AsyncTask class either using static method or using instance of that method.
Thanks Deepak
精彩评论