用JSON填充的ListView替换JSON填充的TextView

时间:2013-12-12 17:11:24

标签: java android json listview textview

我有一个JSON请求,它返回来自youtube的回复,其中包含特定视频的评论。我目前有3个文本视图:一个用于名称/上传者,一个用于内容,一个用于发布日期 - 然后填充来自我的JSON响应的数据。

我的问题是 - 只显示第一条评论,发布日期和上传者。

我相信我需要用列表视图替换我的textviews并解析3个字段 - 我根本不知道如何。

JAVA

公共类播放器扩展了YouTubeBaseActivity实现 YouTubePlayer.OnInitializedListener {

public static final String API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.player);
    String title = getIntent().getStringExtra("title");
    String uploader = getIntent().getStringExtra("uploader");
    String viewCount = getIntent().getStringExtra("viewCount");
    TextView titleTv = (TextView) findViewById(R.id.titleTv);
    TextView uploaderTv = (TextView) findViewById(R.id.uploaderTv);
    TextView viewCountTv = (TextView) findViewById(R.id.viewCountTv);

    titleTv.setText(title);
    uploaderTv.setText("by" + uploader + " |");
    viewCountTv.setText(viewCount + " views");
    YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubeplayerview);
    youTubePlayerView.initialize(API_KEY, this);



    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });
    GetYouTubeUserCommentsTask task = new GetYouTubeUserCommentsTask(handler , viewCount);




    task.execute();
}

@Override
public void onInitializationFailure(Provider provider,
        YouTubeInitializationResult result) {
    Toast.makeText(getApplicationContext(), "onInitializationFailure()",
            Toast.LENGTH_LONG).show();
}

@Override
public void onInitializationSuccess(Provider provider,
        YouTubePlayer player, boolean wasRestored) {
    if (!wasRestored) {
        String video_id = getIntent().getStringExtra("id");
        player.loadVideo(video_id);
    }
}

public final class GetYouTubeUserCommentsTask extends
AsyncTask<Void, Void, Void> {

    public static final String LIBRARY = "CommentsLibrary";
    private final Handler replyTo;
    private final String username;
    String video_id = getIntent().getStringExtra("id");

    public GetYouTubeUserCommentsTask(Handler replyTo, String username) {
        this.replyTo = replyTo;
        this.username = username;
    }


    @Override
    protected Void doInBackground(Void... arg0) {
        try {

            HttpClient client = new DefaultHttpClient();

            HttpUriRequest request = new HttpGet(
                    "http://gdata.youtube.com/feeds/api/videos/"
                            + video_id
                            + "/comments?v=2&alt=json&start-index=1&max-results=50&prettyprint=true");

            HttpResponse response = client.execute(request);

            String jsonString = StreamUtils.convertToString(response
                    .getEntity().getContent());

            JSONObject json = new JSONObject(jsonString);
            JSONArray jsonArray = json.getJSONObject("feed").getJSONArray(
                    "entry");

            List<Comments> comments = new ArrayList<Comments>();

            for (int i = 0; i < jsonArray.length(); i++) { 
                JSONObject entry = jsonArray.getJSONObject(i); 
                JSONArray authorArray = entry.getJSONArray("author");

                JSONObject publishedObject = entry.getJSONObject("published");
                    String published = publishedObject.getString("$t");

                    JSONObject contentObject = entry.getJSONObject("content");
                    String content = contentObject.getString("$t");

                JSONObject authorObject = authorArray.getJSONObject(0);
                JSONObject nameObject = authorObject.getJSONObject("name");
                String name = nameObject.getString("$t");






                comments.add(new Comments(name, content, published));


                CommentsLibrary lib = new CommentsLibrary(published, content, name);

            Bundle data = new Bundle();
            data.putSerializable(LIBRARY, lib);

            Message msg = Message.obtain();
            msg.setData(data);
            replyTo.sendMessage(msg);
            }
        } catch (ClientProtocolException e) {
            Log.e("Feck", e);
        } catch (IOException e) {
            Log.e("Feck", e);
        } catch (JSONException e) {
            Log.e("Feck", e);
        }
        return null;
    }


    @Override
    protected void onPostExecute(Void result) {
        ListView comments = (ListView) findViewById(R.id.comments); 
        comments.setFilterText(com.idg.omv.domain.CommentsLibrary.getName());


    }
}

}

CommentsLibrary

public class CommentsLibrary implements Serializable{
    // The username of the owner of the comment
    private static String name;
    // The  comment
        private static String content;
    // The date the comment was published
    private static String published;

    public CommentsLibrary(String name, String content, String published) {
        this.name = name;
        this.content = content;
        this.published = published;
    }

    /**
     * @return the user name
     */
    public static String getName() {
        return name;
    }

    /**
     * @return the videos
     */
    public static String getContent() {
        return content;
    }

    /**
     * @return the videos
     */
    public static String getPublished() {
        return published;
    }
}

XML

   <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_weight="1"
        android:gravity="left"
        android:text="" />
    <TextView
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:layout_weight="1"
        android:gravity="left"
        android:text="" />
    <TextView
        android:id="@+id/published"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/content"
        android:layout_weight="1"
        android:gravity="left"
        android:text="" />

2 个答案:

答案 0 :(得分:0)

您需要在布局中添加列表视图,并使用ArrayAdapter填充它。这是一个教程,向您展示如何 - http://www.vogella.com/articles/AndroidListView/article.html#arrayAdapter

答案 1 :(得分:0)

继续我之前的问题@ JSON String is incorrectly mapped to textviews

的回答

首先,您需要在布局xml中使用listview

<ListView
 android:id="@+id/list"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 />

将列表声明为实例变量

 ArrayList<CommentsLibrary> list = new ArrayList<CommentsLibrary>();

然后

 for (int i = 0; i < jsonArray.length(); i++) {
 JSONObject jsonObject = jsonArray.getJSONObject(i);
 String name = jsonObject.optString("name","defaultValue");
 String content = jsonObject.optString("content","defaultValue");
 String published = jsonObject.optString("published","defaultValue");
 list.add(new CommentsLibrary(name, content, published));
 }

然后初始化listview

ListView lv =(ListView)findViewById(R.id.list);
CustomAdapter cus = new CustomAdapter(ActivityName.this,list);
lv.setAdapter(cus);

使用3个textviews定义自定义布局。 (list_item.xml)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="18dp"
        android:layout_marginTop="31dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignBottom="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView2"
        android:layout_alignBottom="@+id/textView2"
        android:layout_alignParentRight="true"
        android:layout_marginRight="24dp"
        android:text="TextView" />

</RelativeLayout>

然后通过扩展基本适配器来定义自定义适配器。覆盖getView会使自定义布局膨胀并在那里设置文本视图。

public class CustomAdapter extends BaseAdapter
{
    LayoutInfalter mInflater; 
    ArrayList<CommentsLibrary> list;  
    public CustomAdapter(Context context,ArrayList<CommentsLibrary> list)
    {
     mInflater = LayoutInfalter.from(context);
     this.list = list;  
    } 
    @Override
public int getCount() {
    // TODO Auto-generated method stub
    return list.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(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    ViewHolder holder;
    if(convertView==null)
    {
        convertView =minflater.inflate(R.layout.list_item, parent,false);
        holder = new ViewHolder();
        holder.tv1 = (TextView) convertView.findViewById(R.id.textView1);
        holder.tv2 = (TextView) convertView.findViewById(R.id.textView2);
        holder.tv3 = (TextView) convertView.findViewById(R.id.textView3); 
        convertView.setTag(holder);
    }
    else
    {
        holder= (ViewHolder) convertView.getTag();
    }
    holder.tv1.setText(list.get(position).getName());
            holder.tv2.setText(list.get(position).getContent());
            holder.tv3.setText(list.get(position).getPublished());
    return convertView;
}
static class ViewHolder
{
    TextView tv1,tv2,tv3

}
}