getview layoutinflater中的NullpointerException

时间:2013-08-22 12:08:04

标签: android baseadapter

BaseAdapter

中显示数据时,在CustomListview中获取空指针异常
public View getView(final int position, View convertView, ViewGroup parent){
            // TODO Auto-generated method stub
         ViewHolder holder = null;       

                 LayoutInflater layout = getActivity().getLayoutInflater();

          convertView = layout.inflate(R.layout.player, null);           

          View vi = convertView;

            if (vi == null) {

                    holder = new ViewHolder();              

                    holder.tProduct = (TextView) vi.findViewById(R.id.product);
                    holder.tTitle = (TextView) vi.findViewById(R.id.title);            

                    convertView.setTag(holder);                     

            } else {
                 holder = (ViewHolder) vi.getTag();
            }


            holder.tProduct.setText(description.get(position));
                holder.tTitle.setText(title.get(position));         

        return vi;
        }

3 个答案:

答案 0 :(得分:0)

试试这个::

LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);  
            View layout = layoutInflater.inflate(R.layout.new_popup_layout, null);  

希望它能帮助!!

答案 1 :(得分:0)

你必须做那样的事情

在您的适配器中

创建一个myInflater变量,如下所示

private LayoutInflater myInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

然后在您的代码中使用myInflater而不是您正在使用的getActivity()

convertView = myInflater.inflate(R.layout.player, null);

修改

对我而言,这样做是最有效的,因为你只获得一次上下文。如果您将其直接放在getView中,则每次调用getView时都会访问它。

答案 2 :(得分:0)

尝试这样的事情..

public View getView(final int position, View convertView, ViewGroup parent){
        // TODO Auto-generated method stub
     ViewHolder holder;       



      View vi = convertView;

        if (vi == null) {
                  // here mContext is you got in constructor from activity
                LayoutInflater layout = mContext.getLayoutInflater();

                vi= layout.inflate(R.layout.player,parent,false);  

                holder = new ViewHolder();              

                holder.tProduct = (TextView) vi.findViewById(R.id.product);
                holder.tTitle = (TextView) vi.findViewById(R.id.title);            

                vi.setTag(holder);                     

        } else {
             holder = (ViewHolder) vi.getTag();
        }


        holder.tProduct.setText(description.get(position));
        holder.tTitle.setText(title.get(position));         

    return vi;
    }