Sunday, 15 December 2013

NetworkOnMainThreadException

Why we get NetworkOnMainThreadException?

This exception is found in your logcat, when you  read the data through network in main thread
The long process data reading is not run in your main thread
To solve this problem, having following ways:

1)Strictmode:
------------
write this code in your oncreate method

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll()
.build();

StrictMode.setThreadPolicy(policy); 
 
2)AsynkTask
-------------------
write your code inside doInBackground() method

 private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
     protected Long doInBackground(URL... urls) {
         
// write your code here
         return ;
     } 
};


3)Using Thread 
----------------
 
 Thread thread = new Thread(new Runnable(){
    @Override
    public void run() {
        try {
            //Your code goes here
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

thread.start(); 


No comments:

Post a Comment