我收到以下错误
尝试调用虚方法'void
android.widget.StackView.setAdapter(android.widget.Adapter)'为null
对象参考
在这条线上
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加载它。如@Tauqir所述,您需要像这样膨胀正确的xml:
View view = inflater.inflate(R.layout.events_layout, null);
stackView = (StackView) view.findViewById(R.id.stackView1);
return view;
关于java - 尝试在空对象引用上调用虚拟方法'',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32924971/