android.os.NetworkOnMainThreadException and java.lang.reflect.InvocationTargetException

618 views Asked by At

I have a problem. I want to know where did the android.os.NetworkOnMainThreadException and
java.lang.reflect.InvocationTargetException Exception come from !

Please, I'm new to Android and I need your help guys!

My LogCat:

12-19 13:00:27.049: E/AndroidRuntime(1170): FATAL EXCEPTION: main
12-19 13:00:27.049: E/AndroidRuntime(1170): java.lang.IllegalStateException: Could not execute method of the activity
12-19 13:00:27.049: E/AndroidRuntime(1170):     at android.view.View$1.onClick(View.java:3633)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at android.view.View.performClick(View.java:4240)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at android.view.View$PerformClick.run(View.java:17721)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at android.os.Handler.handleCallback(Handler.java:730)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at android.os.Looper.loop(Looper.java:137)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at android.app.ActivityThread.main(ActivityThread.java:5103)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at java.lang.reflect.Method.invokeNative(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at java.lang.reflect.Method.invoke(Method.java:525)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at dalvik.system.NativeStart.main(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170): Caused by: java.lang.reflect.InvocationTargetException
12-19 13:00:27.049: E/AndroidRuntime(1170):     at java.lang.reflect.Method.invokeNative(Native Method)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at java.lang.reflect.Method.invoke(Method.java:525)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at android.view.View$1.onClick(View.java:3628)
12-19 13:00:27.049: E/AndroidRuntime(1170):     ... 11 more
12-19 13:00:27.049: E/AndroidRuntime(1170): Caused by: android.os.NetworkOnMainThreadException
12-19 13:00:27.049: E/AndroidRuntime(1170):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at libcore.io.IoBridge.connect(IoBridge.java:112)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at java.net.Socket.connect(Socket.java:842)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-19 13:00:27.049: E/AndroidRuntime(1170):     at com.ensem.sehaty.MainActivity.recupererListMed(MainActivity.java:58)
12-19 13:00:27.049: E/AndroidRuntime(1170):     ... 14 more
12-19 13:05:27.366: I/Process(1170): Sending signal. PID: 1170 SIG: 9

MainActivity.java

public class MainActivity extends Activity {

    Button btnRecupListMed = null;
    ListView listeMed = null;

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

        btnRecupListMed = (Button) findViewById(R.id.btnListMed);
        listeMed = (ListView) findViewById(R.id.listMed);   
    }

    public void recupererListMed(View v){

        BufferedReader br = null;
        StringBuffer sb = new StringBuffer("");

        try {
            HttpClient client = new DefaultHttpClient();
            HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
            HttpGet get = new HttpGet();
            URI uri = new URI("http://105.153.20.252");
            get.setURI(uri);
            HttpResponse reponse = client.execute(get);
            InputStream is = reponse.getEntity().getContent();
            br = new BufferedReader(new InputStreamReader(is));
            String str = br.readLine();
            while(str != null){
                sb.append(str);
                sb.append("\n");
                str = br.readLine();
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
            System.out.println("Erreur 1");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            System.out.println("Erreur 2");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Erreur 3");
        }

        try {
            //ArrayList<HashMap<String, String>> medecins = new ArrayList<HashMap<String, String>>();

            JSONArray js = new JSONArray(sb.toString());
            List<String> listM = new ArrayList<String>();
            for(int i=0; i<js.length(); i++){               
                    JSONObject jsObj = js.getJSONObject(i);
                    String nom = jsObj.getString("NOMMED");
                    listM.add(nom);
            }

                 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                            android.R.layout.simple_list_item_1, R.id.listMed, listM);

                listeMed.setAdapter(adapter);   

        } catch (JSONException e) {
            e.printStackTrace();
            System.out.println("Erreur 4");
        }
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

activity_main.xml

<TextView
        android:text="@string/lbl_sehaty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />

    <Button 
        android:id="@+id/btnListMed"
        android:text="@string/lbl_btn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:onClick="recupererListMed"
        />

    <ListView
              android:id="@+id/listMed"
              android:layout_height="wrap_content"
              android:layout_width="match_parent"
              android:layout_marginTop="60dp">

         </ListView>

And my Manifest contains the following permission

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

Thanks.

1

There are 1 answers

0
vipul mittal On

This error comes when you try to make a server call on UI thread.

You should create an AsyncTask and put your server call in it.

And on click of button call execute on the object of asynctask.

Ex:

public class ServiceTask extends AsyncTask<String, Void, String> {



    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {

        BufferedReader br = null;
        StringBuffer sb = new StringBuffer("");

        try {
            HttpClient client = new DefaultHttpClient();
            HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
            HttpGet get = new HttpGet();
            URI uri = new URI("http://105.153.20.252");
            get.setURI(uri);
            HttpResponse reponse = client.execute(get);
            InputStream is = reponse.getEntity().getContent();
            br = new BufferedReader(new InputStreamReader(is));
            String str = br.readLine();
            while(str != null){
                sb.append(str);
                sb.append("\n");
                str = br.readLine();
            }


        } catch (URISyntaxException e) {
            e.printStackTrace();
            System.out.println("Erreur 1");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            System.out.println("Erreur 2");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Erreur 3");
        }
        return sb;
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            //ArrayList<HashMap<String, String>> medecins = new ArrayList<HashMap<String, String>>();

            JSONArray js = new JSONArray(result.toString());
            List<String> listM = new ArrayList<String>();
            for(int i=0; i<js.length(); i++){               
                    JSONObject jsObj = js.getJSONObject(i);
                    String nom = jsObj.getString("NOMMED");
                    listM.add(nom);
            }

                 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                            android.R.layout.simple_list_item_1, R.id.listMed, listM);

                listeMed.setAdapter(adapter);   

        } catch (JSONException e) {
            e.printStackTrace();
            System.out.println("Erreur 4");
        }
    }
}

And inside your onClick event:

public void recupererListMed(View v){
   new ServiceTask().execute();
}

This will execute doInBackground method on a different thread and once result is fetched onPostExecute is called on UI thread.