2014-03-30 35 views
0

我從json格式獲取服務器的response。我如何在listview中顯示回覆。如何在列表視圖中顯示JSON響應

代碼:

public class MainActivity extends Activity { 
    private static String url = "http://api.androidhive.info/contacts/"; 

    @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(); 
     InputStream is = null; 
     StrictMode.setThreadPolicy(policy); 

     new JSONParse().execute(); 

    } 

    private class JSONParse extends AsyncTask<String, String, JSONObject> { 
     private ProgressDialog pDialog; 

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

      pDialog = new ProgressDialog(MainActivity.this); 
      pDialog.setMessage("Getting Data ..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 

     } 

     @Override 
     protected JSONObject doInBackground(String... args) { 

      JSONParser jParser = new JSONParser(); 

      // Getting JSON from URL 
      JSONObject json = jParser.getJSONFromUrl(url); 
      return json; 
     } 

     @Override 
     protected void onPostExecute(JSONObject json) { 
      pDialog.dismiss(); 

     } 
    } 
} 

public class JSONParser { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    // constructor 
    public JSONParser() { 

    } 

    public JSONObject getJSONFromUrl(String url) { 

     // Making HTTP request 
     try { 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent();   

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
      System.out.println("sb:"+sb); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     // try parse the string to a JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // return JSON String 
     return jObj; 

    } 
} 
+0

如果你正確地按照教程,你不會問這個問題。 http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ – Raghunandan

+0

爲JSON解析教程我剛剛推薦這個網站,這將回答你所有的問題。 http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ –

+0

請檢查我的文章與最終編輯它將工作 – Raghunandan

回答

0

這是沒有必要

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
      .permitAll().build(); 
InputStream is = null; 
StrictMode.setThreadPolicy(policy); 

而且@SuppressLint("NewApi")表明您忍住皮棉警告。有些功能僅適用於新的API。檢查你的最小sdk版本。

,以顯示它您需要的ListView列表響應

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical"> 
    <!-- Main ListView 
     Always give id value as list(@android:id/list) 
    --> 
    <ListView 
     android:id="id/list" // id is list 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"/> 

</LinearLayout> 

然後在的onCreate

ListView lv; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    lv= (ListView) findViewById(R.id.list); 
    new JSONParse().execute(); 
}  

更改此

private class JSONParse extends AsyncTask<String, String, JSONObject> 

private class JSONParse extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> 

請確保您有這些

public class MainActivity extends Activity { 

    private static String url = "http://api.androidhive.info/contacts/"; 
    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"; 

doInbackground你需要解析JSON

@Override 
    protected ArrayList<HashMap<String, String>> doInBackground(String... args) { 
     ArrayList<HashMap<String, String>> contactList= new ArrayList<HashMap<String,String>>(); 
     JSONParser jParser = new JSONParser(); 

     // Getting JSON from URL 
     JSONObject json = jParser.getJSONFromUrl(url); 
      try { 
       contacts = json.getJSONArray(TAG_CONTACTS); 

       // looping through All Contacts 
       for (int i = 0; i < contacts.length(); i++) { 
        JSONObject c = contacts.getJSONObject(i); 

        String id = c.getString(TAG_ID); 
        String name = c.getString(TAG_NAME); 
        String email = c.getString(TAG_EMAIL); 
        String address = c.getString(TAG_ADDRESS); 
        String gender = c.getString(TAG_GENDER); 

        // Phone node is JSON Object 
        JSONObject phone = c.getJSONObject(TAG_PHONE); 
        String mobile = phone.getString(TAG_PHONE_MOBILE); 
        String home = phone.getString(TAG_PHONE_HOME); 
        String office = phone.getString(TAG_PHONE_OFFICE); 

        // tmp hashmap for single contact 
        HashMap<String, String> contact = new HashMap<String, String>(); 

        // adding each child node to HashMap key => value 
        contact.put(TAG_ID, id); 
        contact.put(TAG_NAME, name); 
        contact.put(TAG_EMAIL, email); 
        contact.put(TAG_PHONE_MOBILE, mobile); 

        // adding contact to contact list 
        contactList.add(contact); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     return contactList; 
    } 

然後

@Override 
    protected void onPostExecute(ArrayList<HashMap<String, String>> result) { 
     super.onPostExecute(result); 
     // Dismiss the progress dialog 
     if (pDialog.isShowing()) 
      pDialog.dismiss(); 
     ListAdapter adapter = new SimpleAdapter(
       MainActivity.this, result, 
       R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL, 
         TAG_PHONE_MOBILE }, new int[] { R.id.name, 
         R.id.email, R.id.mobile }); 

     lv.setAdapter(adapter); 
    } 

list_item.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" 
    android:padding="10dp" 
    android:paddingLeft="10dp" 
    android:paddingRight="10dp" > 

    <!-- Name Label --> 

    <TextView 
     android:id="@+id/name" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:paddingBottom="2dip" 
     android:paddingTop="6dip" 
     android:textColor="#43bd00" 
     android:textSize="16sp" 
     android:textStyle="bold" /> 

    <!-- Email label --> 
    <TextView 
     android:id="@+id/email" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:paddingBottom="2dip" 
     android:textColor="#acacac" /> 

    <!-- Mobile number label --> 
    <TextView 
     android:id="@+id/mobile" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:gravity="left" 
     android:text="Mobile: " 
     android:textColor="#5d5d5d" 
     android:textStyle="bold" /> 

</LinearLayout>