Search code examples
androidjsonmultithreadingnetwork-connection

How to solve issue with mainthread


I try get JSON data from a php file

public void connect(){
    System.out.println("%%%%%%%%%%%%%%%%%1" );
    Thread t = new Thread(){

        @Override
        public void run() {

    try {

        System.out.println("%%%%%%%%%%%%%%%%%2" );
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(params, 0);
        HttpClient httpClient = new DefaultHttpClient(params);
        String urlString = "http://url";
        //prepare the HTTP GET call 
        HttpGet httpget = new HttpGet(urlString);
        //get the response entity
        HttpEntity entity = httpClient.execute(httpget).getEntity();
        System.out.println("%%%%%%%%%%%%%%%%%3" );
        if (entity != null) {
            //get the response content as a string
            String response = EntityUtils.toString(entity);
            //consume the entity
            entity.consumeContent();

            // When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
            httpClient.getConnectionManager().shutdown();

            //return the JSON response

            JSONArray jsonarray = new JSONArray(response); 
            JSONObject jb =(JSONObject) jsonarray.getJSONObject(0);
            String name= jb.getString("name");
            String punkt = jb.getString("punktezahl");

             //String name = jsonarray.getString("name");
             System.out.println("HEEEEEEEEEEEEEEEEEEEEEEEEEEEE" + name);
             fuehrender.setText(name);
             punkte.setText(punkt);
               }



    }catch (Exception e) {
        e.printStackTrace();
    }
}

};
t.start();
}

If I do like this I get the message that only the original Thread that created a view hierarchy can touch its views.

So because of this error message I tried it like this:

public void connect(){
    System.out.println("%%%%%%%%%%%%%%%%%1" );
    runOnUiThread(new Runnable() {

        @Override
        public void run() {

    try {

        System.out.println("%%%%%%%%%%%%%%%%%2" );
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(params, 0);
        HttpClient httpClient = new DefaultHttpClient(params);
        String urlString = "http://url";
        //prepare the HTTP GET call 
        HttpGet httpget = new HttpGet(urlString);
        //get the response entity
        HttpEntity entity = httpClient.execute(httpget).getEntity();
        System.out.println("%%%%%%%%%%%%%%%%%3" );
        if (entity != null) {
            //get the response content as a string
            String response = EntityUtils.toString(entity);
            //consume the entity
            entity.consumeContent();

            // When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
            httpClient.getConnectionManager().shutdown();

            //return the JSON response

            JSONArray jsonarray = new JSONArray(response); 
            JSONObject jb =(JSONObject) jsonarray.getJSONObject(0);
            String name= jb.getString("name");
            String punkt = jb.getString("punktezahl");

             //String name = jsonarray.getString("name");
             System.out.println("HEEEEEEEEEEEEEEEEEEEEEEEEEEEE" + name);
             fuehrender.setText(name);
             punkte.setText(punkt);
               }



    }catch (Exception e) {
        e.printStackTrace();
    }
}

});

}
}

Now, I get the NetworkOnMainThread error message.. How to break through this doom loop?


Solution

  • You have a runOnUiThread. Remove it. It should be used only for updating ui not for http get request.

    Using AsyncTask is a better option. Make the http get request in doInBackground and parse the response also. You can return the result in doInbackground which is a param to onPostExecute.

    So you can update ui in onPostExecute which is invoked on the ui thread.

    http://developer.android.com/reference/android/os/AsyncTask.html

    Example:

    To invoke

    new TheTask().execute(); // in ui thread
    

    Make AsyncTask an inner class of activity

    class TheTask extends AsyncTask<Void,Void,String>
    {
    
        @Override
        protected String doInBackground(Void... params1) {
            String response = null; 
                try {
                    HttpParams params = new BasicHttpParams();
                    HttpConnectionParams.setSoTimeout(params, 0);
                    HttpClient httpClient = new DefaultHttpClient(params);
                    String urlString = "http://url";
                    HttpGet httpget = new HttpGet(urlString);
                    HttpEntity entity = httpClient.execute(httpget).getEntity();
                    response = EntityUtils.toString(entity);
                    httpClient.getConnectionManager().shutdown();
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                    }
            return response;
        }
    
        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
             JSONArray jsonarray = new JSONArray(result; 
             JSONObject jb =(JSONObject) jsonarray.getJSONObject(0);
             String name= jb.getString("name");
             String punkt = jb.getString("punktezahl");
             fuehrender.setText(name);
             punkte.setText(punkt);
        }
    
    }