本文介绍了尝试在空对象引用上调用虚拟方法''的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到以下错误
在此行
stackView.setAdapter(adapter);
完整的片段 EventsFragment.java 是
public class EventsFragment extends android.support.v4.app.Fragment {
private StackView stackView;
private ArrayList<Stack_Items> list;
TypedArray eventLogo ;
String eventName[];
@Nullable
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
eventLogo= getResources().obtainTypedArray(R.array.event_stack_icon);
eventName = getResources().getStringArray(R.array.event_stack);
stackView = (StackView) getActivity().findViewById(R.id.stackView1);
list = new ArrayList<Stack_Items>();
//Adding items to the list
for (int i = 0; i < eventLogo.length(); i++) {
list.add(new Stack_Items(eventName[i], eventLogo.getResourceId(i,-1)));
}
//Calling adapter and setting it over stackView
Stack_Adapter adapter = new Stack_Adapter(getActivity().getApplicationContext(), list );
stackView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return inflater.inflate(R.layout.events_layout, null);
}
}
Stack_Adapter.java
public class Stack_Adapter extends BaseAdapter {
ArrayList<Stack_Items> arrayList;
LayoutInflater inflater;
ViewHolder holder = null;
public Stack_Adapter(Context context, ArrayList<Stack_Items> arrayList) {
this.arrayList = arrayList;
this.inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return arrayList.size();
}
@Override
public Stack_Items getItem(int pos) {
return arrayList.get(pos);
}
@Override
public long getItemId(int pos) {
return pos;
}
@Override
public View getView(int pos, View view, ViewGroup parent) {
if (view == null) {
view = inflater.inflate(R.layout.stack_layout, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.textView1);
holder.image = (ImageView) view.findViewById(R.id.imageView1);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText(arrayList.get(pos).getName());
holder.image.setBackgroundResource(arrayList.get(pos).getImage());
return view;
}
public class ViewHolder {
TextView text;
ImageView image;
}
}
Stack_Items
public class Stack_Items {
String name;
Integer image;
public Stack_Items(String name, Integer image) {
this.name = name;
this.image = image;
}
public String getName() {
return name;
}
public int getImage() {
return image;
}
}
推荐答案
您正在做:
stackView = (StackView) getActivity().findViewById(R.id.stackView1);
您的 stackView
为 null
. getActivity().findViewById
返回 null
.
为什么要使用 getActivity()
?
stackView
在哪里?您应该从正确的xml加载它.
Where is the stackView
? You should load it from the right xml.
如@Tauqir所述,您需要像这样膨胀正确的xml:
as @Tauqir mentioned, you need to inflate the right xml like this:
View view = inflater.inflate(R.layout.events_layout, null);
stackView = (StackView) view.findViewById(R.id.stackView1);
return view;
这篇关于尝试在空对象引用上调用虚拟方法''的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!