0

I have Async Task for get json array to load spinner. But in the onPostExecute I got NetworkOnMainThreadException error.

//Error in here

 while ((line = reader.readLine()) != null) 
 {
  builder.append(line) ;
 }

here is my onPostExecute. response is a Http responce. What is the error here?

   protected void onPostExecute(String result) {

             BufferedReader reader;
            try {
    reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

                 StringBuilder builder = new StringBuilder();

                 String line = null;

                    //Error in here
                 while ((line = reader.readLine()) != null) 
                    {
                     builder.append(line) ;
                    }



                 JSONTokener tokener = new JSONTokener(builder.toString());
                 JSONArray finalResult = new JSONArray(tokener);

                 final String[] items = new String[finalResult.length()]; 

                    // looping through All Contacts
                    for(int i = 0; i < finalResult.length(); i++){

                        JSONObject c = finalResult.getJSONObject(i);

                        items[i]=c.getString("data_name");

                    }

                    ArrayAdapter<String> adapter = new ArrayAdapter<String> (activity, android.R.layout.simple_spinner_item, items);       

                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                    spin.setAdapter(adapter);



            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } 


            super.onPostExecute(result);

            //activity.startActivity(new Intent(activity, wanted.class));


            if (dialog != null)
                 dialog.dismiss();   

        }
Sajitha Rathnayake
  • 1,688
  • 3
  • 26
  • 47

1 Answers1

3

You should move your :

reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// ..
while ((line = reader.readLine()) != null) 

to

AsyncTask.doInBackground()

this is where your network operations must take place, onPostExecute is on UI thread

marcinj
  • 48,511
  • 9
  • 79
  • 100