0

I'm trying a simple example : http://www.vogella.com/articles/AndroidJSON/article.html

But got an error .. Can anyone tell me why I get this error : http://puu.sh/1mGz1

pkdkk
  • 3,905
  • 8
  • 44
  • 69
  • Check Vogella blog for [**NetworkOnMainThreadException**](http://www.vogella.com/blog/2012/02/22/android-strictmode-networkonmainthreadexception/) or check here on Stackoverflow itself: http://stackoverflow.com/search?q=Android+NetworkOnMainThreadException – Paresh Mayani Nov 05 '12 at 10:15

2 Answers2

1

use AsyncTask for making server request from UI Thread so change your code as:

  ///Your code...
      @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        new LongOperation().execute("");
      }

    private class LongOperation extends AsyncTask<String, Void, String> {

          @Override
          protected String doInBackground(String... params) {
                //call readtwitterFeed() method here
                String readtwitterFeed=readtwitterFeed(); 

                return readtwitterFeed;
          }      

          @Override
          protected void onPostExecute(String result) {      
                try {
                  JSONArray jsonArray = new JSONArray(result);
                  Log.i(ParseJSON.class.getName(),
                      "Number of entries " + jsonArray.length());
                  for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    Log.i(ParseJSON.class.getName(), jsonObject.getString("text"));
                  }
                } catch (Exception e) {
                  e.printStackTrace();
                }     
          }

          @Override
          protected void onPreExecute() {
          }

          @Override
          protected void onProgressUpdate(Void... values) {
          }
    }
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
0

You are trying to make data request on the main thread. Use AsyncTask to do it.
Or add this 2 line in the onCreate() method to bypass it.

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

I recommend using asynctask though.

Community
  • 1
  • 1
Lazy Ninja
  • 22,342
  • 9
  • 83
  • 103