2013-04-23 65 views
0

我想從昨天開始,讓我的應用程序獲取由PHP文件生成的一些JSON數據,然後在列表視圖中顯示此數據。如何顯示Android的Web服務中的JSON列表

PHP文件是使用編碼方法的編碼數據:

echo json_encode($results); 

瀏覽器瀏覽查看源由file.php產生的JSON看起來像這樣:

["","CSD1939","CSD1939"] 

JSONLint(一個很好的工具)驗證這是一個正確的JSON格式。

當我試圖使用我的應用程序從Web服務中獲取此JSON時,我首先將其作爲字符串獲取,但我無法將其傳遞到適配器並使其正確顯示。

我只管理到現在創建一個顯示字符串數組的列表視圖。

獲取此JSON數據並將其顯示在列表中的最佳方式是什麼?

package com.example.ams; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.StatusLine; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.content.Context; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 

public class ViewClasses extends Activity { 

    @SuppressLint("NewApi") 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.view_classes); 

     new GetInfo().execute(); 

     // ==============Functionality Start==================== 
     // final ListView listview = (ListView) findViewById(R.id.listview); 
    } 

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

     protected String doInBackground(Void... params) { 
      // Fetch the JSON from the web and we pass it as a string to 
      // the ON POST EXECUTE method 
      StringBuilder builder = new StringBuilder(); 
      HttpClient client = new DefaultHttpClient(); 
      HttpGet httpGet = new HttpGet(
        "file.php?get=XXX"); 
      try { 
       HttpResponse response = client.execute(httpGet); 
       StatusLine statusLine = response.getStatusLine(); 
       int statusCode = statusLine.getStatusCode(); 
       if (statusCode == 200) { 
        HttpEntity entity = response.getEntity(); 
        InputStream content = entity.getContent(); 
        BufferedReader reader = new BufferedReader(
          new InputStreamReader(content)); 
        String line; 
        while ((line = reader.readLine()) != null) { 
         builder.append(line); 
        } 
       } else { 
        Log.e(this.toString(), "Failed to download file"); 
       } 
      } catch (ClientProtocolException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      return builder.toString(); 
     } 

     protected void onPostExecute(String result) { 
      // Here it should turn it into a JSON and then display it in a list. 
      // Gets the list view 
      final ListView listview = (ListView) findViewById(R.id.listview); 

      // Converts the String to a JSON array 
      System.out.println(result); 
      JSONArray jsonArray; 
      try { 
       System.out.println(result); 
       jsonArray = new JSONArray(result); 

       Log.i(ViewClasses.class.getName(), "Number of entries " 
         + jsonArray.length()); 
       for (int i = 0; i < jsonArray.length(); i++) { 
        JSONObject jsonObject = jsonArray.getJSONObject(i); 
        Log.i(ViewClasses.class.getName(), 
          jsonObject.getString("text")); 

        // Converts JSON array to Java Array 
        final ArrayList<String> list = new ArrayList<String>(); 
        // values instead of jsonArray 
        if (jsonArray != null) { 
         int len = jsonArray.length(); 
         for (int i1 = 0; i1 < len; i1++) { 
          list.add(jsonArray.get(i).toString()); 
         } 
        } 
        final StableArrayAdapter adapter = new StableArrayAdapter(
          getApplicationContext(), 
          android.R.layout.simple_list_item_1, list); 
        listview.setAdapter(adapter); 
       } 
      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    } 

    private class StableArrayAdapter extends ArrayAdapter<String> { 

     HashMap<String, Integer> mIdMap = new HashMap<String, Integer>(); 

     public StableArrayAdapter(Context context, int textViewResourceId, 
       List<String> objects) { 
      super(context, textViewResourceId, objects); 
      for (int i = 0; i < objects.size(); ++i) { 
       mIdMap.put(objects.get(i), i); 
      } 
     } 

     @Override 
     public long getItemId(int position) { 
      String item = getItem(position); 
      return mIdMap.get(item); 
     } 

     @Override 
     public boolean hasStableIds() { 
      return true; 
     } 

    } 
} 

佈局XML文件看起來像這樣

<ListView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/listview" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" /> 

運行這段代碼,我得到一個空白屏幕。

任何幫助,指針,提示將不勝感激

+0

你有在logcat中的任何錯誤? – Simo 2013-04-23 15:18:07

+0

請參閱下面的@Pragnani答案,它是正確的。 – 2013-04-23 18:02:04

回答

1

它只是返回JSONArrayStrings,所以你不應該從它創建JSONObject

JSONObject jsonObject = jsonArray.getJSONObject(i); 

這將導致ExceptionJSONArray不含JSONObjects

所以解析這樣

ArrayList<String> list = new ArrayList<String>(); 
for (int i = 0; i < jsonArray.length(); i++) { 
    list.add(jsonArray.get(i).toString()); 
} 
+0

就是這樣!非常感謝。 – 2013-04-23 15:21:53