简体   繁体   中英

Asyntask in JSON Parsing

This is my sample code, where I make a json parsing class to parse data from a given link.

package com.billosuch.listviewblogpost;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class ListViewBlogPost extends Activity {

    // url to make request
    private static String url = "http://api.androidhive.info/contacts/";

    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_GENDER = "gender";
    private static final String TAG_PHONE = "phone";
    private static final String TAG_PHONE_MOBILE = "mobile";
    private static final String TAG_PHONE_HOME = "home";
    private static final String TAG_PHONE_OFFICE = "office";

    // contacts JSONArray
    JSONArray contacts = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ArrayList<SearchResults> searchResultss = new ArrayList<SearchResults>();
        final ListView lv1 = (ListView) findViewById(R.id.ListView01);

        JSONParser jparser = new JSONParser();
        JSONObject json = jparser.getJSONFromUrl(url);

        // looping through All Contacts

        Log.d("*********oSR", "B4 TRy");

        try {

            contacts = json.getJSONArray(TAG_CONTACTS);

            for (int i = 0; i < contacts.length(); i++) {

                SearchResults oSR = new SearchResults();
                JSONObject c = contacts.getJSONObject(i);

                oSR.setId(c.getString(TAG_ID));
                oSR.setName(c.getString(TAG_NAME));
                oSR.setEmail(c.getString(TAG_EMAIL));
                oSR.setAddress(c.getString(TAG_ADDRESS));
                oSR.setGender(c.getString(TAG_GENDER));

                JSONObject phone = c.getJSONObject(TAG_PHONE);

                oSR.setPhone_mobile(phone.getString(TAG_PHONE_MOBILE));
                oSR.setPhone_home(phone.getString(TAG_PHONE_HOME));
                oSR.setPhone_office(phone.getString(TAG_PHONE_OFFICE));

                searchResultss.add(oSR);

                Log.d("*********oSR", oSR.getName());

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

        Log.d("*********oSR", "AFTER TRy");
        lv1.setAdapter(new MyCustomBaseAdapter(this, searchResultss));

    }


}

This code showing me warning to do this in Asyntask. I want it to be supported on ICS and JellyBean.

Skipped 391 frames!  The application may be doing too much work on its main thread.

You should use a asynctask for this purpose and move the network related code to doinBackground()

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

Load your asynctask on the UI thread as

  new TheTask().execute()

Asynctask Class.

  class TheTask extends AsyncTask<Void,Void,Void>
  {
  protected void onPreExecute()
  {           super.onPreExecute();
            //display progressdialog.
  } 

   protected void doInBackground(Void ...params)
  {  
        //Network related opearaiton. Do not update ui here

        return null;
  } 

   protected void onPostExecute(Void result)
  {     
            super.onPostExecute(result);
            //dismiss progressdialog.
            //update ui
  } 

 }

You can pass the URL to the conbstructor of the asynctask or directly to doInbackground()

You are currently making a server request in the UI thread. While the app waits for the server response, your UI freezes and that's a bad user experience. Use an AsyncTask in order to load your data in another thread and update the UI when you get the server response.

here is an example

Make LongOperation class like this.

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

      @Override
      protected String doInBackground(String... params) {
            JSONParser jparser = new JSONParser();
    JSONObject json = jparser.getJSONFromUrl(url);

    // looping through All Contacts

    Log.d("*********oSR", "B4 TRy");

    try {

        contacts = json.getJSONArray(TAG_CONTACTS);

        for (int i = 0; i < contacts.length(); i++) {

            SearchResults oSR = new SearchResults();
            JSONObject c = contacts.getJSONObject(i);

            oSR.setId(c.getString(TAG_ID));
            oSR.setName(c.getString(TAG_NAME));
            oSR.setEmail(c.getString(TAG_EMAIL));
            oSR.setAddress(c.getString(TAG_ADDRESS));
            oSR.setGender(c.getString(TAG_GENDER));

            JSONObject phone = c.getJSONObject(TAG_PHONE);

            oSR.setPhone_mobile(phone.getString(TAG_PHONE_MOBILE));
            oSR.setPhone_home(phone.getString(TAG_PHONE_HOME));
            oSR.setPhone_office(phone.getString(TAG_PHONE_OFFICE));

            searchResultss.add(oSR);

            Log.d("*********oSR", oSR.getName());

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


            return null;
      }      

      @Override
      protected void onPostExecute(String result) {
             lv1.setAdapter(new MyCustomBaseAdapter(this, searchResultss));
            //might want to change "executed" for the returned string passed into onPostExecute() but that is upto you
      }

      @Override
      protected void onPreExecute() {
      }

      @Override
      protected void onProgressUpdate(Void... values) {

      }
}

Change your code like below

package com.billosuch.listviewblogpost;

    import java.util.ArrayList;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.ListView;

    public class ListViewBlogPost extends Activity {

        // url to make request
        private static String url = "http://api.androidhive.info/contacts/";

        // JSON Node names
        private static final String TAG_CONTACTS = "contacts";
        private static final String TAG_ID = "id";
        private static final String TAG_NAME = "name";
        private static final String TAG_EMAIL = "email";
        private static final String TAG_ADDRESS = "address";
        private static final String TAG_GENDER = "gender";
        private static final String TAG_PHONE = "phone";
        private static final String TAG_PHONE_MOBILE = "mobile";
        private static final String TAG_PHONE_HOME = "home";
        private static final String TAG_PHONE_OFFICE = "office";
        final ListView lv1;
        ArrayList<SearchResults> searchResultss;

        // contacts JSONArray
        JSONArray contacts = null;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            searchResultss = new ArrayList<SearchResults>();
            lv1 = (ListView) findViewById(R.id.ListView01);

           new MyAsync(Youractivity.this).execute();

        }





    public class MyAsync extends AsyncTask<Void, Integer, Void> {



            public MyAsync(Activity activity) {
                this.activity = activity;


                context = activity;
                dialog = new ProgressDialog(context);


            }

            /** progress dialog to show user that the backup is processing. */
            private ProgressDialog dialog;
            /** application context. */
            private Activity activity;
            private Context context;



            protected void onPreExecute() {
                // TODO Auto-generated method stub
                super.onPreExecute();






            }

            @Override
            protected Void doInBackground(Void... params) {
                // TODO Auto-generated method stub


     JSONParser jparser = new JSONParser();
            JSONObject json = jparser.getJSONFromUrl(url);

            // looping through All Contacts

            Log.d("*********oSR", "B4 TRy");

            try {

                contacts = json.getJSONArray(TAG_CONTACTS);

                for (int i = 0; i < contacts.length(); i++) {

                    SearchResults oSR = new SearchResults();
                    JSONObject c = contacts.getJSONObject(i);

                    oSR.setId(c.getString(TAG_ID));
                    oSR.setName(c.getString(TAG_NAME));
                    oSR.setEmail(c.getString(TAG_EMAIL));
                    oSR.setAddress(c.getString(TAG_ADDRESS));
                    oSR.setGender(c.getString(TAG_GENDER));

                    JSONObject phone = c.getJSONObject(TAG_PHONE);

                    oSR.setPhone_mobile(phone.getString(TAG_PHONE_MOBILE));
                    oSR.setPhone_home(phone.getString(TAG_PHONE_HOME));
                    oSR.setPhone_office(phone.getString(TAG_PHONE_OFFICE));

                    searchResultss.add(oSR);

                    Log.d("*********oSR", oSR.getName());

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

            Log.d("*********oSR", "AFTER TRy");


                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                // TODO Auto-generated method stub
                super.onPostExecute(result);

                            lv1.setAdapter(new MyCustomBaseAdapter(this, searchResultss));



                             }



          }
    }

You can use async task like this...

package com.billosuch.listviewblogpost;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class ListViewBlogPost extends Activity {

// url to make request
private static String url = "http://api.androidhive.info/contacts/";

// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";

// contacts JSONArray
JSONArray contacts = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ArrayList<SearchResults> searchResultss = new ArrayList<SearchResults>();
    final ListView lv1 = (ListView) findViewById(R.id.ListView01);

new MyTask().execute(url);

class MyTask extends AsyncTask<String, Void, String> {

    ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pDialog = new ProgressDialog(SocialActivity.this);
        pDialog.setMessage("Loading...");
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

                      JSONParser jparser = new JSONParser();
                      JSONObject json = jparser.getJSONFromUrl(params[0]);
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }

        if (null == result || result.length() == 0) {
            showToast("No data found from web!!!");
            YourActivity.this.finish();
        } else {

            try {
contacts = json.getJSONArray(TAG_CONTACTS);

        for (int i = 0; i < contacts.length(); i++) {

            SearchResults oSR = new SearchResults();
            JSONObject c = contacts.getJSONObject(i);

            oSR.setId(c.getString(TAG_ID));
            oSR.setName(c.getString(TAG_NAME));
            oSR.setEmail(c.getString(TAG_EMAIL));
            oSR.setAddress(c.getString(TAG_ADDRESS));
            oSR.setGender(c.getString(TAG_GENDER));

            JSONObject phone = c.getJSONObject(TAG_PHONE);

            oSR.setPhone_mobile(phone.getString(TAG_PHONE_MOBILE));
            oSR.setPhone_home(phone.getString(TAG_PHONE_HOME));
            oSR.setPhone_office(phone.getString(TAG_PHONE_OFFICE));

            searchResultss.add(oSR);

            Log.d("*********oSR", oSR.getName());

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

    Log.d("*********oSR", "AFTER TRy");
    lv1.setAdapter(new MyCustomBaseAdapter(this, searchResultss));

}


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM