2012-03-04 185 views
0

我一直试图将Json解析为ListView,但是当我这样做的时候,我得到了;Android:在列表视图中解析Json

03-04 14:43:45.345: E/log_tag(16519): Error parsing data org.json.JSONException: No value for items 

它以某种方式无法将项目从Json对象中取出。

这是我用的代码;

getJSON.java

import java.io.BufferedReader; 
    import java.io.InputStream; 
    import java.io.InputStreamReader; 

    import org.apache.http.HttpEntity; 
    import org.apache.http.HttpResponse; 
    import org.apache.http.client.HttpClient; 
    import org.apache.http.client.methods.HttpPost; 
    import org.apache.http.impl.client.DefaultHttpClient; 
    import org.json.JSONException; 
    import org.json.JSONObject; 

    import android.util.Log; 

    public class getJSON { 

     public static JSONObject getJSONfromURL(String url){ 
      InputStream is = null; 
      String result = ""; 
      JSONObject jArray = null; 

      //http post 
      try{ 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost(url); 
        HttpResponse response = httpclient.execute(httppost); 
        HttpEntity entity = response.getEntity(); 
        is = entity.getContent(); 

      }catch(Exception e){ 
        Log.e("NO CONNECTION", "Error in http connection "+e.toString()); 
      } 

      //convert response to string 
      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(); 
        result=sb.toString(); 
      }catch(Exception e){ 
        Log.e("CANT CONVERT DATA", "Error converting result "+e.toString()); 
      } 

      try{ 

       jArray = new JSONObject(result);    
      }catch(JSONException e){ 
        Log.e("CANT READ DATA", "Error parsing data "+e.toString()); 
      } 

      return jArray; 
     } 
} 

的listview.java

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.listplaceholder); 
     ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); 

     //Get the data (see above) 
     JSONObject json = getJSON.getJSONfromURL("http://gdata.youtube.com/feeds/api/users/UKFDubstep/uploads?v=2&alt=jsonc"); 


       try{ 



        final JSONArray array = json.getJSONArray("items"); 

         //Loop the Array 
       for(int i=0;i < array.length();i++){       

        HashMap<String, String> map = new HashMap<String, String>(); 
        JSONObject e = array.getJSONObject(i); 

        map.put("id", String.valueOf(i)); 
        map.put("title", "" + e.getString("title")); 
        map.put("viewCount", "Views: " + e.getString("viewCount")); 
        mylist.add(map); 
      } 
       }catch(JSONException e)  { 
       Log.e("log_tag", "Error parsing data "+e.toString()); 
       } 

       ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.dubstep, 
         new String[] { "title", "viewCount" }, 
         new int[] { R.id.item_title, R.id.item_subtitle }); 

     setListAdapter(adapter); 

     final ListView lv = getListView(); 
     lv.setTextFilterEnabled(true); 
     lv.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      @SuppressWarnings("unchecked") 
      HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position); 
      Toast.makeText(dubstep.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 

      } 
     }); 

    } 

我不知道哪里出了问题。

任何帮助? 谢谢。

编辑: JSON输出

03-04 15:30:29.955: I/json(19109): {"error":{"message":"Response contains no content type","errors":[{"internalReason":"Response contains no content type","domain":"GData","code":"missingContentType"}],"code":400},"apiVersion":"2.1"} 

编辑JSON链路; HTTP://gdata.youtube.com/feeds/api/users/UKFDubstep/uploads V = 2 & ALT = jsonc

+0

您可以发布原始JSON字符串吗?看起来你拥有的JSON格式并不像你期望的那样。 – xandy 2012-03-04 14:10:21

+0

我在那里看到一个网址 - 我想你会想要做你的网络活动的UI线程。我不知道你的JSON包如何工作,但“项目”嵌套在“数据”中 - 你需要以嵌套的方式引用它,“data.items”也许? – dldnh 2012-03-04 14:17:30

回答

1

通过查看JSON结果(通过打开示例url),我看到'items'在另一个JSONObject中。所以我相信你需要做的:

JSONObject data = json.getJSONObject('data'); 
JSONArray array = data.getJSONArray('items'); 
+0

然后我得到这个; getExtractedText处于非活动状态InputConnection并且没有数据值 – 2012-03-04 14:22:43

+0

您可以发布确切的异常吗?你可以试着做的只是打印到LogCat json.toString(),这样你就可以看到并确保它实际上拥有你期望的所有数据。 – YuviDroid 2012-03-04 14:28:17

+0

完成但不知道它是如何得到这种方式 – 2012-03-04 14:40:42

0

你不需要getJSON.java,只有你应该做的,使其工作是这样的:

private static String URL = "http://gdata.youtube.com/feeds/api/users/UKFDubstep/uploads?v=2&alt=jsonc"; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.listplaceholder); 

    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); 

     try{     
       HttpClient httpclient = new DefaultHttpClient(); 
       httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 
       HttpGet request = new HttpGet(URL); 
       HttpResponse response = httpclient.execute(request); 
       HttpEntity resEntity = response.getEntity(); 
       String _response = EntityUtils.toString(resEntity); // content will be consume only once 
       Log.i(".......",_response); 
       JSONObject json = new JSONObject(_response); 
       JSONArray jarray = json.getJSONArray("items");      
        //Loop the Array 
       for(int i=0;i < array.length();i++){       

        HashMap<String, String> map = new HashMap<String, String>(); 
        JSONObject e = array.getJSONObject(i); 

        map.put("id", String.valueOf(i)); 
        map.put("title", "" + e.getString("title")); 
        map.put("viewCount", "Views: " + e.getString("viewCount")); 
        mylist.add(map); 
     } 
      }catch(JSONException e)  { 
      Log.e("log_tag", "Error parsing data "+e.toString()); 
      } 

      ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.dubstep, 
        new String[] { "title", "viewCount" }, 
        new int[] { R.id.item_title, R.id.item_subtitle }); 

    setListAdapter(adapter); 

    final ListView lv = getListView(); 
    lv.setTextFilterEnabled(true); 
    lv.setOnItemClickListener(new OnItemClickListener() { 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
     @SuppressWarnings("unchecked") 
     HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position); 
     Toast.makeText(dubstep.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 

     } 
    }); 

} 

但你应该现在,解析JSON数据应不会在UI线程中执行。您需要扩展AsyncTask并在doInBackgound()方法中执行那项工作,因此您可以在单独的线程中进行解析,而不是在UI中执行解析... AsyncTask