自定义ListView中的空指针片段

时间:2016-11-04 12:21:36

标签: android nullpointerexception

在将自定义适配器设置为listview时获取NullPointerException。 我的ListView在片段中。 .................................................. .................................................. ........................................

第1课:

public class Fragment_chats extends Fragment {
ListView lv;
    String[] namem={"Gauri","Jayesh","Nitya","Rupali","Lalit","Poonam"};
    Integer[] imgm=    {R.mipmap.a,R.mipmap.b,R.mipmap.c,R.mipmap.d,R.mipmap.e,R.mipmap.f};

public Fragment_chats() {
    // Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    }


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
super.onCreate(savedInstanceState);
   View v= inflater.inflate(R.layout.fragment_fragment_chats, container, false);
    lv=(ListView)getActivity().findViewById(R.id.lv);
    customList cl=new customList(getActivity(),imgm,namem);
    lv.setAdapter(cl);
    return v;
}

}

第2课:

class customList extends ArrayAdapter
{
    Activity act;
    String[] na;
    Integer[] img;
public customList(Activity context, Integer[] resource, String[] objects) {
    super(context, R.layout.chats, objects);
    act=context;
    na=objects;
    img=resource;

}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null)
    {
        convertView = View.inflate (act,R.layout.chats, null);
    }
    ImageView iv= (ImageView) convertView.findViewById(R.id.imageView);
    TextView name=(TextView)convertView.findViewById(R.id.textView1);
    TextView chat=(TextView)convertView.findViewById(R.id.textView2);
    iv.setImageResource(img[position]);
    name.setText(na[position]);
    chat.setText("chat");

    return convertView;
}
}

自定义布局为R.layout.chats和  片段布局为R.layout.fragment_fragment_chats

2 个答案:

答案 0 :(得分:3)

onCreateView方法

中有错误
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
super.onCreate(savedInstanceState);
   View v= inflater.inflate(R.layout.fragment_fragment_chats, container, false);
    lv=(ListView)getActivity().findViewById(R.id.lv); //<-this line has error
    customList cl=new customList(getActivity(),imgm,namem);
    lv.setAdapter(cl);
    return v;
}

替换此行

lv=(ListView)getActivity().findViewById(R.id.lv);

用这个

lv=(ListView)v.findViewById(R.id.lv);

答案 1 :(得分:2)

  

当应用程序尝试使用时抛出NullPointerException   具有空值的对象引用。

您应该调用 View对象而不是getActivity()

<强>不

lv=(ListView)getActivity().

<强>不要

lv=(ListView)v.