2013-06-27 5 views
0

나는 안드로이드에서 "Youtube Gdata JSON을 파싱하는"의 실례를 찾고 listview를 채색하려고 노력 해왔다.Youtube Gdata json을 ListView로 파싱

나는 this question을 읽고 있고, 나는 거의 4 오류를 제외하고 작업이 ..

  1. ITEM_TITLE
  2. item_subtitle
  3. setListAdapter
  4. 위에서 getListView

    import android.app.Activity; 
    import android.os.Bundle; 
    import android.util.Log; 
    import android.view.Menu; 
    import android.view.View; 
    import android.widget.AdapterView; 
    import android.widget.ListAdapter; 
    import android.widget.ListView; 
    import android.widget.SimpleAdapter; 
    import android.widget.Toast; 
    import org.json.JSONArray; 
    import org.json.JSONException; 
    import org.json.JSONObject; 
    import java.util.ArrayList; 
    import java.util.HashMap; 
    
    public class listview extends Activity { 
    
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.listview_main); 
    
    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); 
    
    //Get the data (see above) 
    JSONObject json = getJSON.getJSONfromURL("https://gdata.youtube.com/feeds/api/videos?q=random&max-results=50&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(); 
    //final ListView lv = getListView(); 
    lv.setTextFilterEnabled(true); 
    lv.setOnItemClickListener(new AdapterView.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(listview.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 
    
        } 
    }); 
    
    } 
    
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
        // Inflate the menu; this adds items to the action bar if it is present. 
        getMenuInflater().inflate(R.menu.listview, menu); 
        return true; 
        } 
    } 
    

그것은 어떤 도움에 감사드립니다 "Cannot resolve symbol 'item_title' and 'item_subtitle'
"Cannot resolve method 'setListAdapter(android.widget.ListAdapter)'

말한다, 감사합니다!

+0

촬영? 당신은 같은 것을 게시 할 수 있습니까? 좀 더 관련성이 높은 코드를 게시하십시오. – Raghunandan

+0

이 말씀이 있으십니까? 'new int [] {R.id.item_title, R.id.item_subtitle}); ' –

+0

전체 코드와 스택 추적을 게시하십시오. – Raghunandan

답변

5

귀하의 활동 종류가 ListActivity으로 연장되지 않습니다. 따라서 오류 3 및 4

네트워크 관련 작업에는 AsyncTask을 사용해야합니다. 메인 UI 스레드에서 네트워크 관련 작업을 실행할 수 없습니다.

이미지에 느린 로딩을 사용해야합니다. 하지만 샘플 난 thumbnail에 대한 비트 맵의 ​​ArrayList를 사용했습니다. 메모리 누수가 발생할 수 있습니다. 따라서 게으른 로딩을 사용하십시오. 귀하의 요구 사항에 따라 아래 수정하십시오.

예 :

public class MainActivity extends Activity { 

    Button b; 
    ListView lv; 
    ArrayList<String> msg = new ArrayList<String>(); 
    ArrayList<String> title = new ArrayList<String>(); 
    ArrayList<Bitmap> thumb = new ArrayList<Bitmap>(); 
    ProgressDialog pd; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     lv= (ListView) findViewById(R.id.lv); 
     pd = new ProgressDialog(MainActivity.this); 
     pd.setTitle("Loading.."); 
     b= (Button) findViewById(R.id.button1); 
     b.setOnClickListener(new OnClickListener() 
     { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       new TheTask().execute(); 
      } 

     }); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 
    public void getData() 
    { 
     HttpClient httpclient = new DefaultHttpClient(); 
     httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 
     HttpGet request = new HttpGet("https://gdata.youtube.com/feeds/api/videos?q=random&max-results=50&v=2&alt=jsonc"); 
     // HttpGet request = new HttpGet("http://gdata.youtube.com/feeds/api/users/mbbangalore/uploads?v=2&alt=jsonc");  
     try 
     { 
     HttpResponse response = httpclient.execute(request); 
     HttpEntity resEntity = response.getEntity(); 
     String _response=EntityUtils.toString(resEntity); // content will be consume only once 

     JSONObject json = new JSONObject(_response); 

     JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items"); 
     for (int i = 0; i < jsonArray.length(); i++) { 
      JSONObject jsonObject = jsonArray.getJSONObject(i); 

      String title1 = jsonObject.getString("title"); 
      title.add(title1); 
      String thumbUrl = jsonObject.getJSONObject("thumbnail").getString("sqDefault"); 
      URL url1 = new URL(thumbUrl); 
      Bitmap bmp = BitmapFactory.decodeStream(url1.openConnection().getInputStream()); 
      thumb.add(bmp); 
      String url; 
      try { 

       url = jsonObject.getJSONObject("player").getString("default"); 
       msg.add(url); 
      } catch (JSONException ignore) { 
      } 
     } 
     } 
     catch(Exception e1) 
      { 
       e1.printStackTrace(); 
      } 

     httpclient.getConnectionManager().shutdown(); 
    } 
    class TheTask extends AsyncTask<Void,Void,Void> 
    { 

    @Override 
    protected void onPostExecute(Void result) { 
     // TODO Auto-generated method stub 
     super.onPostExecute(result); 
     pd.dismiss(); 
     YouTubeAdapter you = new YouTubeAdapter(MainActivity.this,msg,title,thumb); 
     lv.setAdapter(you); 
    } 

    @Override 
    protected void onPreExecute() { 
     // TODO Auto-generated method stub 
     super.onPreExecute(); 
     pd.show(); 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     // TODO Auto-generated method stub 
     getData(); 
     return null; 
    } 

    } 
} 

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity" > 

    <ListView 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:id="@+id/lv" 
     android:layout_above="@+id/button1" 
     /> 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_centerHorizontal="true" 
     android:text="Button" /> 

</RelativeLayout> 

YouTubeAdapter

public class YouTubeAdapter extends BaseAdapter{ 

    Context mContext; 
    Intent intent; 
    LayoutInflater mInflater; 
    ArrayList<String> mVideo= new ArrayList<String>(); 
    ArrayList<String> mTitle= new ArrayList<String>(); 
    ArrayList<Bitmap> mThumb= new ArrayList<Bitmap>(); 

    public YouTubeAdapter(Context context,ArrayList<String> a,ArrayList title,ArrayList thumb) { 
     mContext=context; 
     mVideo=a; 
     mTitle = title; 
     mThumb= thumb; 
     mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    } 

    @Override 
    public int getCount() { 
     // TODO Auto-generated method stub 
     return mVideo.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     // TODO Auto-generated method stub 
     return position; 
    } 

    @Override 
    public long getItemId(int position) { 
     // TODO Auto-generated method stub 
     return position; 
    } 

    @Override 
    public View getView(final int position, View arg1, ViewGroup arg2) { 
     ViewHolder vh; 

     if(arg1==null) 
     { 
      arg1=mInflater.inflate(R.layout.video, null); 
      vh= new ViewHolder(); 
      vh.tv=(TextView)arg1.findViewById(R.id.tvv); 
      vh.iv=(ImageView)arg1.findViewById(R.id.ivv); 
      arg1.setTag(vh); 
     } 
     else 
     { 
      vh= (ViewHolder)arg1.getTag(); 
     } 
     vh.tv.setText(mTitle.get(position)); 
     vh.iv.setImageBitmap(mThumb.get(position)); 
     return arg1; 
    } 

    static class ViewHolder 
    { 
     TextView tv; 
     ImageView iv; 
    } 
} 

video.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    > 

    <TextView 
     android:id="@+id/tvv" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center" 
     android:textColor="#000000" 
     android:textSize="13dp" /> 

    <ImageView 
     android:id="@+id/ivv" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     /> 

</LinearLayout> 
,691,363 (210)

스냅 어디 코드에서 item_title``이다

enter image description here

+0

그래도이 오류가 발생합니다. '기호 변수 tvv '를 찾을 수 없습니다.'기호 변수 ivv '를 찾을 수 없습니다.'기호 변수 비디오를 찾을 수 없습니다. '레이아웃 폴더에'video.xml'을 만들었습니다. –

+0

@RobertdeJonge 이드의 ID입니다. 'video.xml'의 텍스트 뷰. 그래서 만약 당신이 video.xml과 그 안에 textviews가 있는지 확인하십시오. – Raghunandan

+0

@RobertdeJonge는 res 폴더에'video.xml' 파일을 만들고 그 안에 위의'video.xml' 코드를 붙여 넣습니다. – Raghunandan