这是我的示例代码,我在其中创建了一个 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.