自定义ArrayAdapter NullpointerException

时间:2014-01-03 16:33:22

标签: android arraylist nullpointerexception android-arrayadapter

我的自定义阵列适配器出了问题:

我的NullpointerException方法中有getView()

我已经发现ArrayList似乎没有问题,因为没有适配器它可以正常工作。

我的适配器

public class ArrayAdapterCusPostlist extends ArrayAdapter<Post> {

    Context mContext;
    ArrayList<Post> postListe;


    public ArrayAdapterCusPostlist(Context mContext, int layoutResourceId, ArrayList<Post>pList) {

        super(mContext, layoutResourceId, pList);
        postListe = pList;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView==null){
            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
            convertView = inflater.inflate(R.layout.rowpost, parent, false);
        }
        Post curpost=postListe.get(position);

        if(curpost!=null){
        TextView textViewItem = (TextView) convertView.findViewById(R.id.nickname2);
        textViewItem.setText(curpost.getName());
        textViewItem.setTag(curpost.getName());
        }

        return convertView;

    }

}

并且:如果ArrayList为空,因为我没有调用add()方法,则没有NullPointerException。这是我的数组列表:

    ArrayList<Post> PostList=new ArrayList<Post>();
    PostList.add(new Post("Name", "Zeit", "Post", getResources().getDrawable(R.drawable.winter), getResources().getDrawable(R.drawable.winter)));
    mPostList = (ListView) findViewById(R.id.postliste);
    final ArrayAdapterCusPostlist adapter2 = new ArrayAdapterCusPostlist(this, R.layout.rowpost, PostList);
    mPostList.setAdapter(adapter2); 

谢谢!

1 个答案:

答案 0 :(得分:0)

Context mContext;未初始化

 Context mContext;
 LayoutInflater inflater;
 public ArrayAdapterCusPostlist(Context mContext, int layoutResourceId, ArrayList<Post>pList) {
 super(mContext, layoutResourceId, pList);
 this.mContext =mContext;
 inflater = LayoutInflater.from(context); // initialize here. no need for context initialization if you have this here.
 }  

最好使用ViewHolder模式

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if(convertView==null){
        convertView = inflater.inflate(R.layout.rowpost, parent, false);
        holder = new ViewHolder();
        holder.textViewItem = (TextView) convertView.findViewById(R.id.nickname2);
        convertView.setTag(holder);
    }
    else
    {
          holder = (ViewHolder) convertView.getTag();
    }
    Post curpost=postListe.get(position);

     holder.textViewItem.setText(curpost.getName());
     holder.textViewItem.setTag(curpost.getName());
    }

    return convertView;

static class ViewHolder
{
     TextView textViewItem;
}
}