例外:尝试在空对象引用上调用虚拟方法'android.view.LayoutInflater android.app.Activity.getLayoutInflater()'

时间:2015-04-20 17:09:20

标签: android android-listview

我收到此异常Attempt to invoke virtual method 'android.view.LayoutInflater android.app.Activity.getLayoutInflater()' on a null object reference但我能找到原因。

在mainactivity中我创建了一个ListView元素,结构是:

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/list"
/>

我为listview创建了一个自定义Adapter类,

class ListItem
{
    public String shortDescription;
    public String type;
    public String time;
    public int imageId;

    public ListItem(String sd, String type, String time, Integer imageId)
    {
        this.shortDescription = sd;
        this.type = type;
        this.time = time;
        this.imageId = imageId;
    }
}


public class CustomList extends ArrayAdapter<Object>{

    private Activity context;
    private ListItem listItem[];

    public CustomList(Activity context, ListItem li[]){
        super(context, R.layout.rowlayout, li);
        this.listItem = li;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent)
    {
        LayoutInflater inflater = context.getLayoutInflater();
        View rowView = inflater.inflate(R.layout.rowlayout, null, true);
        TextView sd = (TextView)rowView.findViewById(R.id.sd);
        TextView type = (TextView)rowView.findViewById(R.id.type);
        TextView days = (TextView)rowView.findViewById(R.id.days);
        ImageView icon = (ImageView)rowView.findViewById(R.id.icon);

        sd.setText(listItem[position].shortDescription);
        type.setText(listItem[position].type);
        days.setText(listItem[position].time);
        icon.setImageResource(listItem[position].imageId);
        return rowView;
    }

我在我的MainActivity类中调用它,

public class MainActivity extends ActionBarActivity {

    ListView listView;
    ListItem listItem[] = new ListItem[2];
    Integer[] imageId = {R.drawable.ic_launcher};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listItem[0] = new ListItem("test", "test", "test", imageId[0]);
        listItem[1] = new ListItem("test1", "test1", "test1", imageId[0]);

        CustomList adapter = new CustomList(MainActivity.this, listItem);
        listView = (ListView)findViewById(R.id.list);
        listView.setAdapter(adapter);
    }
}

我在自定义Adapter类中得到异常,位于 LayoutInflater inflater = context.getLayoutInflater(); 。但变量 context 在构造函数调用本身中初始化。为什么会抛出异常?

1 个答案:

答案 0 :(得分:6)

contextnull。忘记初始化。把它当作:

public CustomList(Activity context, ListItem li[]){
        super(context, R.layout.rowlayout, li);
        this.listItem = li;
        this.context=context; //<< initialize here
    }