gpt4 book ai didi

android - 异常 : Attempt to invoke virtual method 'android.view.LayoutInflater android.app.Activity.getLayoutInflater()' on a null object reference

转载 作者:行者123 更新时间:2023-11-29 14:47:38 26 4
gpt4 key购买 nike

我得到这个异常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 创建了一个自定义适配器类,

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 是在构造函数调用本身中初始化的。为什么会抛出异常?

最佳答案

contextnull。忘记初始化。按如下方式进行:

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

关于android - 异常 : Attempt to invoke virtual method 'android.view.LayoutInflater android.app.Activity.getLayoutInflater()' on a null object reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29754118/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com