提问人:Jyothi Gowniwari 提问时间:6/7/2019 最后编辑:PhantômaxxJyothi Gowniwari 更新时间:6/7/2019 访问量:30
ListView.setAdapter(android.widget.ListAdapter)' 在 android 中的空对象引用上 [duplicate]
ListView.setAdapter(android.widget.ListAdapter)' on a null object reference in android [duplicate]
问:
嗨,在下面单击此片段我的列表视图获取空指针的地方。 如果这是正常活动,它正在工作 fine.it 导致我的应用程序崩溃
任何人都可以帮助我在哪里犯了错误。
public class HomeFragement extends Fragment {
EditText et_building;
TextView Add;
ListView lv;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
public HomeFragement() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
((NavigationViewActivity) getActivity()).setActionBarTitle("ADD BUILDING");
View rootView = inflater.inflate(R.layout.activity_building, container, false);
init();
return rootView;
}
private void clickListener() {
Add.setOnClickListener (new View.OnClickListener ( ) {
@Override
public void onClick(View v) {
String result=et_building.getText ().toString ();
arrayList.add (result);
adapter.notifyDataSetChanged ();
}
});
}
private void init() {
et_building=(EditText)getActivity ().findViewById (R.id.build_name);
Add=(TextView)getActivity ().findViewById (R.id.addbuild);
lv=(ListView)getActivity ().findViewById (R.id.list_building);
arrayList=new ArrayList<String> ();
adapter=new ArrayAdapter<String> (getActivity (),android.R.layout.simple_list_item_1,arrayList);
lv.setAdapter(adapter);
clickListener();
}
答:
0赞
Quick learner
6/7/2019
#1
发现的问题 - 声明 id 时出现问题。 使用
rootView
而不是getActivity()
执行此操作
init(rootView);
而这个方法应该是
private void init(View rootView ) {
et_building=(EditText)rootView.findViewById (R.id.build_name);
Add=(TextView)rootView.findViewById (R.id.addbuild);
lv=(ListView)rootView.findViewById (R.id.list_building);
arrayList=new ArrayList<String> ();
adapter=new ArrayAdapter<String> (getActivity (),android.R.layout.simple_list_item_1,arrayList);
lv.setAdapter(adapter);
clickListener();
}
0赞
Dinesh Shingadiya
6/7/2019
#2
试着把你的代码放进去,就像这样:init()
onCreateView()
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
((NavigationViewActivity) getActivity()).setActionBarTitle("ADD BUILDING");
View rootView = inflater.inflate(R.layout.activity_building, container, false);
et_building=(EditText)rootView.findViewById (R.id.build_name);
Add=(TextView)rootView.findViewById (R.id.addbuild);
lv=(ListView)rootView.findViewById (R.id.list_building);
arrayList=new ArrayList<String> ();
adapter=new ArrayAdapter<String> (getActivity(),android.R.layout.simple_list_item_1,arrayList);
lv.setAdapter(adapter);
return rootView;
}
并使用而不是创建新对象rootView
getActivity()
评论