Skip to content Skip to sidebar Skip to footer

Android App Stopped When Try To Fetch Data From Internet

I'm trying to fetch data from the internet by using HttpGet and HttpClient. However, when I run it in my emulator it immediately shutdown saying 'Unfortunately, AppName has stopped

Solution 1:

android.os.NetworkOnMainThreadException

This means that you are doing network related calls on your Main UI thread.

All Http related calls in your onCreate() have to be moved to an AsyncTask.

Solution 2:

classDownloadTaskextendsAsyncTask<Void,Void,Void>
{
  protectedvoidonPreExecute() 
  {
  super.onPreExecute();  
    //show progress dialog()
  }

 @OverrideprotectedVoiddoInBackground(Void... params) {
   //get data form internet here// put all downloading related code in a method getDownload()// call  getDownload() herereturnnull;
 }

 @OverrideprotectedvoidonPostExecute(Void result) {
  super.onPostExecute(result);
   //dismiss dialog update ui here// uodate ur ui with the downloaded data here
   }
 }

Use the above for AsyncTask

As an alternative you can have a look at this open source project in githup which uses robospice for long running operations. https://github.com/octo-online/robospice.

Solution 3:

Here is the great example by vogela to understand how to use AsynckTask in android.

You can go threw it and put your network relatd call in doBackground of that task.

Hope you got the point.

Post a Comment for "Android App Stopped When Try To Fetch Data From Internet"