我是android新手,我尝试了很多解决方案,但没有任何作用!
请问我的代码有什么问题:
我在NullPointerException
holder.CardContent.setText(card.getString("content"));
我尝试将layoutInflater
从null
更改为parent
,false
ids不是假的!
CardAdapter.java
public class CardAdapter extends ArrayAdapter<ParseObject> {
protected Context mContext;
protected List<ParseObject> mCards;
public CardAdapter(Context context, List<ParseObject> cards) {
super(context, R.layout.card_item, cards);
mContext = context;
mCards = cards;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.card_item, null);
holder = new ViewHolder();
holder.CardContent = (TextView) convertView.findViewById(R.id.cardText);
} else{
holder = (ViewHolder) convertView.getTag();
}
ParseObject card = mCards.get(position);
holder.CardContent.setText(card.getString("content")); // <-- NPE here.
return convertView;
}
private static class ViewHolder{
TextView CardContent;
}
}
logcat的:
at com.kardapps.lifehacks.activities.CardAdapter.getView(CardAdapter.java:64)
at android.widget.AbsListView.obtainView(AbsListView.java:2255)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
at android.widget.ListView.onMeasure(ListView.java:1175)
.......
答案 0 :(得分:1)
问题是holder
至少在开始时是null
。
card
也可以null
,但目前还不清楚。
虽然适配器回收逻辑是正确的,但您忘记了setTag
View
。
回收的逻辑是,您滚动的方式是将已读取/看过的数据保存(使用setTag
)到视图(此处为convertView
)。
然后,每次您传递相同的位置时,使用setTag
检索它们而不是重新创建它们(LayoutInflater.from...
)
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
// This is not an error but using parent you avoid Lint warnings
convertView = LayoutInflater.from(mContext).inflate(R.layout.card_item, parent);
holder = new ViewHolder();
holder.CardContent = (TextView) convertView.findViewById(R.id.cardText);
convertView.setTag(holder); // <-- As suggested for improvement
} else{
holder = (ViewHolder) convertView.getTag();
}
ParseObject card = mCards.get(position);
holder.CardContent.setText(card.getString("content")); // <-- NPE here.
// convertView.setTag(holder); // <-- This line is missing
return convertView;
}
答案 1 :(得分:0)
请参阅此代码:
if(convertView == null){
convertView = LayoutInflater.from(mContext).inflate(R.layout.card_item, null);
holder = new ViewHolder();
holder.CardContent = (TextView) convertView.findViewById(R.id.cardText);
}
else{
holder = (ViewHolder) convertView.getTag();
}
ParseObject card = mCards.get(position);
holder.CardContent.setText(card.getString("content"));
两种可能性:
mCards.get(position);
返回null 答案 2 :(得分:0)
您需要将convertView
的标记设置为holder
- 块中的if
。
if (convertView == null)
{
convertView = LayoutInflater.from(mContext).inflate(R.layout.card_item, null);
holder = new ViewHolder();
holder.CardContent = (TextView) convertView.findViewById(R.id.cardText);
// Add this line
convertView.setTag(holder);
}
您可以在else
- 块中看到,您正在检索标记并将其投射到ViewHolder
。如果尚未设置标记,getTag()
将返回null,从而导致异常。