0

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". Any ideas how to solve this?

The Code:

public class MainActivity extends Activity {

    final String httpPath = "http://www.google.com";    


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView txtContent = (TextView) findViewById(R.id.txtContent);

        TextView tvHttp = (TextView) findViewById(R.id.tvHttp);

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(httpPath);
        try {

            HttpEntity httpEntity = httpclient.execute(httpget).getEntity();

           if (httpEntity != null){
            InputStream inputStream = httpEntity.getContent();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();

            String line = null;

            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }

            inputStream.close();

            tvHttp.setText(stringBuilder.toString());
           }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
      }
AssetManager assetManager = getAssets();


// To load text file
InputStream input;
try {
    input = assetManager.open("dummytext.txt");

     int size = input.available();
     byte[] buffer = new byte[size];
     input.read(buffer);
     input.close();

     // byte buffer into a string
     String text = new String(buffer);

     txtContent.setText(text);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();}

}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

LogCat:

03-08 03:31:17.762: D/AndroidRuntime(892): Shutting down VM
03-08 03:31:17.762: W/dalvikvm(892): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-08 03:31:17.952: E/AndroidRuntime(892): FATAL EXCEPTION: main
03-08 03:31:17.952: E/AndroidRuntime(892): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.appname/com.example.appname.MainActivity}: android.os.NetworkOnMainThreadException
Ram kiran Pachigolla
  • 20,897
  • 15
  • 57
  • 78

3 Answers3

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.

Rahul
  • 44,383
  • 11
  • 84
  • 103
  • How do I move it to an AsyncTask? – user2146966 Mar 08 '13 at 04:04
  • The link I've provided has all the basic info about `AsyncTask`. Once you know that, move all code pieces, related to `Http`(**Internet**) in the `doInBackground()` and call the `execute()` of `AsyncTask` in your `onCreate()`. – Rahul Mar 08 '13 at 04:07
  • check [this example](http://www.javasrilankansupport.com/2012/11/asynctask-android-example-asynctask-in.html), if you like. – Rahul Mar 08 '13 at 04:08
  • I moved all my http related code to an asynctask in the doInBackground(), and I already execute it in my onCreate(), now the app opens, but after a while it shows the error message and closes the app again. And I still havent manage to succesfully fetch the data from the internet to be shown in my textview :( – user2146966 Mar 08 '13 at 04:35
0
    class DownloadTask extends AsyncTask<Void,Void,Void>
{
  protected void onPreExecute() 
  {
  super.onPreExecute();  
    //show progress dialog()
  }

 @Override
 protected Void doInBackground(Void... params) {
   //get data form internet here
   // put all downloading related code in a method getDownload()
   // call  getDownload() here
 return null;
 }

 @Override
  protected void onPostExecute(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.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
0

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.

Shreyash Mahajan
  • 23,386
  • 35
  • 116
  • 188