2012-03-04 3 views
0

Json을 ListView로 구문 분석하려고했지만 그 결과를 얻었습니다.Android : Listview의 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

+0

거기에 URL이 있습니다. UI 작업 스레드에서 네트워크 활동을하고 싶다고 생각합니다. JSON 패키지가 어떻게 작동하는지 모르지만 "items"는 "data"내에 중첩되어 있습니다. 중첩 된 방식으로 참조해야합니까? "data.items"? – dldnh

답변

1

예제 URL을 열어 JSON 결과를 보면 'items'가 다른 JSONObject 내부에 있음을 알 수 있습니다. 그래서 당신이해야 할 생각 :

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 데이터를해야 : 당신은 단지 당신이해야 그것을 작동하도록 getJSON.java을 필요가없는

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

그렇다면 나는 이것을 얻는다. 비활성 InputConnection에 대한 getExtractedText 및 데이터에 대한 값 없음 –

+0

정확한 예외를 게시 할 수 있습니까? LogCat json.toString()을 사용하여 실제로 볼 수있는 모든 데이터가 실제로 있는지 확인할 수 있도록 인쇄하면됩니다. – YuviDroid

+0

완료되었지만 그 길은 어땠는지 몰라. –

0

것은 이것이다 UI 스레드에서 실행되지 않습니다. AsyncTask를 확장하고 doInBackgound() 메서드에서 해당 작업을 수행해야하므로 UI가 아닌 별도의 스레드에서 구문 분석 할 수 있습니다. AsyncTask

관련 문제