2

Im making an android program that parses JSON texts from a source code of a webpage in the internet. It is working in android 2.2 but I need it now to be on android 3.0, which needs to be on the AsyncTask. I have a background about AsyncTask but I'm so confused where to put this and that. Thanks in advance everyone :)

Here is my method in the MainActivity class:

private void jsonStuffs() {
    //JSON PARSER & HOME PAGE TEXTVIEWS

        client = new DefaultHttpClient();

        GetMethodEx test = new GetMethodEx();
        String returned;
        try {
            returned = test.getInternetData();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try{
            String jsonStr = test.getInternetData(); //go to GetMethodEx
                JSONObject obj = new JSONObject(jsonStr);

//////////////////////find temperature in the JSON in the webpage

                String temperature = obj.getString("temperature");
                TextView tvTemp = (TextView)findViewById(R.id.textView);
                tvTemp.setText(temperature);

        }
        //catch (JSONException e) {
             // e.printStackTrace();
            //} 
        catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

The GetMethodEx class is this (this will find the link of the webpage then convert it's source code to text format):

public class GetMethodEx extends Activity {
    public String getInternetData() throws Exception{

        BufferedReader in = null;
        String data = null;
        //

        try{
            HttpClient client = new DefaultHttpClient();
            URI website = new URI("http://nhjkv.comuf.com/json_only.php");
            HttpGet request = new HttpGet();
            request.setURI(website);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String l = "";
            String nl = System.getProperty("line.separator");
            while ((l = in.readLine()) !=null){
                sb.append(l + nl);
            }
            in.close();
            data = sb.toString();
            return data;
        }finally {
            if (in !=null){
                try{
                    in.close();
                    return data;
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

2 Answers2

2

You can do something like this (this code is just for illustration, change it as needed)

class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {
     protected void onPreExecute() {
        // You can set your activity to show busy indicator
        //setProgressBarIndeterminateVisibility(true);
     }

    protected JSONObject doInBackground(String... args) {
        return jsonStuffs();
    }

    protected void onPostExecute(final JSONObject jsonObj) {
        String temperature = jsonObj.getString("temperature");
        TextView tvTemp = (TextView)findViewById(R.id.textView);
        tvTemp.setText(temperature);
        // Stop busy indicator
        //setProgressBarIndeterminateVisibility(false);
    }

To call this task use new MyAsyncTask().execute(); (you can pass String parameters to execute if needed) You can change your jsonStuffs() to return JSONObject

e.g.

private JSONObject jsonStuffs() {

     // ...

     String jsonStr = test.getInternetData(); //go to GetMethodEx
     return new JSONObject(jsonStr);

     // ...
 }
iTech
  • 18,192
  • 4
  • 57
  • 80
1

It is working in android 2.2 but I need it now to be on android 3.0, which needs to be on the AsyncTask.

=> Yes it gives NetworkOnMainThreadException in 3.0 if you make web call without implementing inside Thread such as AsyncTask.

I have a background about AsyncTask but I'm so confused where to put this and that.

=> Simply include web call logic inside doInBackground() method of the AsyncTask, in your case call getInternetData() inside doInBackground().

FYI, you can't update UI straight way while doing long running task inside the doInBackground(). Yes if you want to update UI then do follow any of the below:

  1. Update UI from the onPostExecute() method.
  2. or implement runOnUiThread() inside the doInBackround()
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295