How to fix NetworkonMainThreadException in Android? [duplicate]

可紊 提交于 2019-12-19 05:13:08

问题


I'm creating an project for assignment, I'm new to Android, and I wanted to access json from very common url http://api.androidhive.info/contacts/,

Problem: I'm trying to read the url and fetch and parse the json returned by this url,

I've already added following line into my AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

Preferences: and my android preferences are

<uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
  1. Api level 18
  2. Android 4.3

and this is how I'm trying to read the url

static InputStream is = null;

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

The Error Message

11-02 05:23:47.843: E/AndroidRuntime(2207): FATAL EXCEPTION: main
11-02 05:23:47.843: E/AndroidRuntime(2207): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.me.countrypedia/com.me.countrypedia.MainActivity}: android.os.NetworkOnMainThreadException
11-02 05:23:47.843: E/AndroidRuntime(2207):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-02 05:23:47.843: E/AndroidRuntime(2207):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-02 05:23:47.843: E/AndroidRuntime(2207):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-02 05:23:47.843: E/AndroidRuntime(2207):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)

Also I'm following this tutorial for ListView Example http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/


回答1:


Your Exception actually tells you exactly what you are doing wrong. You are not using another thread to perform NetworkOperations. Instead, you perform the network operation on your UI-Thread, which cannot (does not) work on Android.

Your code that connects to the url should be executed for example inside an AsyncTasks doInBackground() method, off the UI-Thread.

Take a look at this question on how to use the AsyncTask: How to use AsyncTask




回答2:


Updated Answer:

Potentially long running operations such as network operations should be done in a worker thread.

The most effective way to create a worker thread for longer operations is with the AsyncTask class. Simply extend AsyncTask and implement the doInBackground() method to perform the work.

Many libraries are available to do network operations such as Volley, retrofit etc.


Old Answer:

Add following lines in your activity onCreate method

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



回答3:


Use following code.

private class UpdateTask extends AsyncTask<String, String,String> {
     protected String doInBackground(String... urls) {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
        return null;
     }

 }

and in your ManinActivity Use following code.

new UpdateTask().execute();


来源:https://stackoverflow.com/questions/19740604/how-to-fix-networkonmainthreadexception-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!