Question

I have written a simple code on JSON Parsing using AsyncTask. I'm just displaying the response in TextView. I don't know whether it is right or wrong. Its working on GingerBread and showing NetworkOnMainThreadException on JellyBean. If I use StrictMode, its working on JellyBean and getting force close on GingerBread. How to write the code which support above Android 3.0 and below Android 3.0.

public class MainActivity extends Activity {
TextView tv;
Button b;
InputStream is = null;

DefaultHttpClient client;
HttpGet get;
HttpResponse response;
HttpEntity entity;
StringBuffer buffer;

@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  //    StrictMode.setThreadPolicy(policy);
    tv = (TextView) findViewById(R.id.texty);
    b = (Button) findViewById(R.id.buttonGET);

    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            MyOperation mytask = new MyOperation();
            mytask.execute();
        }
    });

}

private class MyOperation extends AsyncTask<String, Void, String> {
    ProgressDialog dialog = new ProgressDialog(MainActivity.this);

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        dialog.setMessage("Loading...");
        dialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        client = new DefaultHttpClient();
        get = new HttpGet("http://www.google.com");
        try {
            response = client.execute(get);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        entity = response.getEntity();

        try {
            is = entity.getContent();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub

        super.onPostExecute(result);
        dialog.dismiss();
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(is));
        StringBuffer buffer = new StringBuffer();
        String line = null;
        do {
            try {
                line = reader.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            buffer.append(line);
        } while (line != null);
        tv.setText(buffer);
    }

}

}

Was it helpful?

Solution

   public class MainActivity extends Activity {
     TextView tv;
    Button b;
    InputStream is = null;

    DefaultHttpClient client;
    HttpGet get;
    HttpResponse response;
HttpEntity entity;
StringBuffer buffer;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //StrictMode.ThreadPolicy policy = new 
  //    StrictMode.setThreadPolicy(policy);
    tv = (TextView) findViewById(R.id.texty);
    b = (Button) findViewById(R.id.buttonGET);

    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            MyOperation mytask = new MyOperation();
            mytask.execute();
        }
    });

}

private class MyOperation extends AsyncTask<String, Void, String> {
    ProgressDialog dialog = new ProgressDialog(MainActivity.this);

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        dialog.setMessage("Loading...");
        dialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
StringBuffer buffer = new StringBuffer();
        // TODO Auto-generated method stub
        client = new DefaultHttpClient();
        get = new HttpGet("http://www.google.com");
        try {
            response = client.execute(get);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        entity = response.getEntity();

        try {
            is = entity.getContent();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    BufferedReader reader = new BufferedReader(
                new InputStreamReader(is));

        String line = null;
        do {
            try {
                line = reader.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            buffer.append(line);
        } while (line != null);

        return buffer.tostring();
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub

        super.onPostExecute(result);
        dialog.dismiss();

        tv.setText(result);
    }}

}

otherwise you are running the read line operation in main thread

OTHER TIPS

Make the InputStream is and Entity entity local field variables in the doInBackground() as return as result the string that you wanna set on the TextView...and on the onPostExecute() you just get the result (the string) and set it in the TextView straight on.

You should read inputStream data in doInBackground function, not in the onPostExecute. So construct StringBuffer in doInBackground append all lines to it and return StringBuffer.toString as result. In onPostExecute you will get what string as parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top