繁体   English   中英

我如何使用列表<data>并将其传递给另一个类

[英]How can i use List<data> and pass it to another class

我在 TweetAdapter.java 中创建了一个自定义适配器。 我已经把代码写成

公共类 TweetAdapter 扩展 ArrayAdapter {

private List<Tweet> tweets;
private Context context;
public TweetAdapter(TweetListActivity ctx, List<Tweet> tweets) {
    super(ctx, R.layout.row_tweet, tweets);
}

@Override
public Tweet getItem(int arg0) {
    return tweets.get(arg0);
}

@Override
public long getItemId(int arg0) {
    return arg0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    if (v == null) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.row_tweet, parent);
    }
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    TextView tweetTitle = (TextView) v.findViewById(R.id.tweetTitle);
    TextView tweetBody = (TextView) v.findViewById(R.id.tweetBody);
    final Tweet currentTweet = tweets.get(position);
    String a = currentTweet.getTitle();
    String b = currentTweet.getBody();
    tweetTitle.setText(a);
    tweetBody.setText(b);
    return v;
}

}

但得到错误

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.Object android.content.Context.getSystemService(java.lang.String)”

在 android.view.LayoutInflater.from(LayoutInflater.java:219)

看起来您的context变量为空,因为它从未被设置。

尝试将您的构造函数修改为:

public TweetAdapter(TweetListActivity ctx, List<Tweet> tweets) {
    super(ctx, R.layout.row_tweet, tweets); 
    context=ctx;
}

解决了

实施的

导入 java.io.Serializable;

在 Tweet.java 中

检查此链接是否对您有帮助:

https://github.com/codelearn-org/CodelearnTwitterApp/blob/master/src/org/codelearn/twitter/TweetAdapter.java

这是相关部分:

public class TweetAdapter extends ArrayAdapter<Tweet> {

     private LayoutInflater inflater;
     private List<Tweet> tweetsLocal;

     public TweetAdapter(Activity activity, List<Tweet> tweets){
         super(activity, R.layout.row_tweet, tweets);
         inflater = activity.getWindow().getLayoutInflater();
         tweetsLocal = tweets;
     }

     @Override
     public View getView(int position, View convertView, ViewGroup parent){
         View row = inflater.inflate(R.layout.row_tweet, parent, false);
         TextView title = (TextView) row.findViewById(R.id.tweetTitle);
         Tweet tweet = tweetsLocal.get(position);
         title.setText(tweet.getTitle());
         TextView body = (TextView) row.findViewById(R.id.textView2);
         body.setText(tweet.getBody());
         return row;
     }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM