I want to parsing Xml from server, but it take long time and finaly throws NetworkOnMainThreadException.
I have using strict mode, but it still thows NetworkOnMainThreadException.
Update :
I try run aplication on emulator,this exception not show.
this exception show when i run aplication on real device.
this my code to parsing xml :
public class ParsingXML extends Thread{
//private Context ctx;
private int status;
private String raw_url;
Context mctx;
public DefaultHandler getMyExampleHandler() {
return myExampleHandler;
}
DefaultHandler myExampleHandler=null;
public ParsingXML(Context ctx , int status){
//this.ctx=ctx;
this.status=status;
this.mctx=ctx;
if(status==constant.GET_LIST_PRODUCT){
raw_url=constant.URL+"listBarang.php";
}
}
public ParsingXML(Context ctx,int status,String id){
this.status=status;
this.mctx=ctx;
if(status==constant.GET_DETAIL_PRODUCT){
raw_url=constant.URL+"detailBarang.php?id="+id;
}
}
public void parse(){
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL(raw_url);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
if(status==constant.GET_LIST_PRODUCT){
myExampleHandler = new ListProductHandler();
}
else if(status==constant.GET_DETAIL_PRODUCT){
myExampleHandler = new DetailProductHandler();
}
xr.setContentHandler(myExampleHandler);
xr.parse(new InputSource(url.openStream()));
} catch (Exception e) {
Toast.makeText(mctx, "Connection Error", Toast.LENGTH_LONG).show();
}
/* Display the TextView. */
}
}
someone can help me please??
any help very apreciated. 🙂
Include your network connection and parsing data to and from different server activities in a separate background thread. There is a class call
AsyncTaskto do this. Include your XML reading code snippets in thedoInBackground()method. After reading all XML file you can show the result inonPostExecute()method.Using the Thread class is deprecated. This is the link to documentation for more details. This process will get rid you from the
NetworkOnMainThreadException.