1

这是我的示例代码,我在其中创建了一个 json 解析类来解析来自给定链接的数据。

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));

    }


}

此代码向我显示在 Asyntask 中执行此操作的警告。我希望它在 ICS 和 JellyBean 上得到支持。

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

5 回答 5

2

您应该为此目的使用 asynctask 并将网络相关代码移动到 doinBackground()

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

在 UI 线程上加载你的 asynctask 为

  new TheTask().execute()

异步任务类。

  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
  } 

 }

您可以将 URL 传递给 asynctask 的构造函数或直接传递给 doInbackground()

于 2013-05-20T12:53:11.853 回答
1

您当前正在 UI 线程中发出服务器请求。当应用程序等待服务器响应时,您的 UI 会冻结,这是一种糟糕的用户体验。使用 anAsyncTask为了在另一个线程中加载您的数据并在您获得服务器响应时更新 UI。

这是一个例子

于 2013-05-20T12:53:26.530 回答
0

像这样制作 LongOperation 类。

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) {

      }
}
于 2013-05-20T12:54:48.520 回答
0

更改您的代码,如下所示

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));



                             }



          }
    }
于 2013-05-20T12:58:11.127 回答
0

您可以像这样使用异步任务...

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));

}


}
于 2013-05-20T12:59:54.203 回答