安卓:在列表视图解析JSON [英] Android: Parse Json in Listview

查看:153
本文介绍了安卓:在列表视图解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力为JSON解析成一个ListView但是当我做,所以我得到;

I have been trying to parse Json into A ListView but when i do so I get;

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

这在某种程度上无法得到项目从JSON对象的。

It somehow can't get the items out of the Json Object.

下面是我的code,我用它;

Here's my code i used for it;

getJSON.java

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

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

            }
        });

    }

我不知道哪里出了问题。

I have no idea where it went wrong.

任何帮助吗?
谢谢你。

Any help? Thanks.

编辑: 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

Edit json link ;http://gdata.youtube.com/feeds/api/users/UKFDubstep/uploads?v=2&alt=jsonc

推荐答案

通过查看JSON结果(通过打开示例URL)我看到'项目'是另一种的JSONObject内。所以我相信你需要做的:

By looking at the JSON result (by opening your example url) I see that 'items' is inside another JSONObject. So I believe you need to do:

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

这篇关于安卓:在列表视图解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆