Android BaseAdapter getView()方法内LayoutFlater中的NullPointerException
下面是我的getView()方法。充气时出现空指针异常。同样的问题有很多答案。这是在片段内部使用的。但这不适合我Android BaseAdapter getView()方法内LayoutFlater中的NullPointerException,android,android-fragments,android-adapter,Android,Android Fragments,Android Adapter,下面是我的getView()方法。充气时出现空指针异常。同样的问题有很多答案。这是在片段内部使用的。但这不适合我 @Override public View getView(int position, View convertView, ViewGroup parent) { Context con = null; View vi=convertView; if(convertView==null){ LayoutInflater inflater
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Context con = null;
View vi=convertView;
if(convertView==null){
LayoutInflater inflater = (LayoutInflater)con.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.stores_listview_layout, null);
}
TextView tv = (TextView)vi.findViewById(R.id.store_name);
tv.setText(storeData.get(position).get("merchantName"));
return vi;
}
我在这里犯了什么错误
更新:这很有效
View vi=convertView;
Context c = null;
if(convertView==null){
LayoutInflater inflater = getLayoutInflater(null);
vi = inflater.inflate(R.layout.stores_listview_layout, parent, false);
}
这是你的错con
尚未初始化,因此它是null
。
您应该将您的活动用作上下文。此处
Context con;///============> here
View vi=convertView;
if(convertView==null){
LayoutInflater inflater = (LayoutInflater)con.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.stores_listview_layout, null);
....
替换上下文con代码>带有
Context con= getApplicationContext();
在这段代码中,您没有初始化上下文变量。首先尝试初始化它。而不是声明上下文con代码>然后使用它-正如前面指出的,这会导致空指针异常,您只需使用convertView.getContext()
检查文件
我只是想了想,但我的第一个想法是行不通的
由于代码位于片段中,因此可以通过
Context con永远不会初始化而不是con.getApplicationContext(),请尝试使用活动的上下文。是否可以粘贴错误日志?此方法位于fragmentstoreData中。get(position)。get(“merchantName”)是否可以检查控制台上打印的值。是否正确?将null传递给GetLayoutFlater(),它最终工作了!感谢Buddy,然后您可以调用getActivity()作为您的上下文。
Context con= getApplicationContext();
public View getView (int position, View convertView, ViewGroup parent){
if( convertView == null ){
//you can access layout inflater by accessing hosting activity
convertView = getActivity().getLayoutInflater().inflate(R.layout.stores_listview_layout, parent, false);
}
TextView tv = (TextView)convertView.findViewById(R.id.store_name);
tv.setText(storeData.get(position).get("merchantName"));
return convertView;
}
LayoutInflater inflater = getLayoutInflater(null);
vi = inflater.inflate(R.layout.stores_listview_layout, parent, false);