我在TweetAdapter.java中创建了一个自定义适配器。我把代码编写为
public class TweetAdapter extends 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:尝试调用虚方法&#39; java.lang.Object android.content.Context.getSystemService(java.lang.String)&#39;在空对象引用上
在android.view.LayoutInflater.from(LayoutInflater.java:219)
答案 0 :(得分:0)
看起来您的context
变量为空,因为它永远不会被设置。
尝试修改您的构造函数:
public TweetAdapter(TweetListActivity ctx, List<Tweet> tweets) {
super(ctx, R.layout.row_tweet, tweets);
context=ctx;
}
答案 1 :(得分:0)
解决
实施
import java.io.Serializable;
Tweet.java中的
答案 2 :(得分:-1)
检查此链接是否有助于您:
以下是相关部分:
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;
}
}