我使用来自网络服务器的信息填充ListView
。
在Activity
中,我的ListAdapeter
工作正常,但当我尝试在Fragment
中使用它时,我无法使用我的适配器。
ListAdapter.java
public class ListAdapter extends BaseAdapter {
MainActivity main;
public ListAdapter(MainActivity main){
this.main = main;
}
//Some methods.
}
MainActivity.java
public class ListReportsFragment extends SupportMapFragment {
@Override
public ListView list;
public ListAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//.........
list = (ListView) findViewById(R.id.list);
adapter = new ListAdapter(this);
list.setAdapter(adapter);
}
//........
}
工作完美,但是,当我尝试在片段中使用它时:
ListReportsFragment
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
list = (ListView) getView().findViewById(R.id.list);
adapter = new ListAdapter(new MainActivity());
list.setAdapter(adapter); //This is the line 58
}
我收到错误
java.lang.NullPointerExceptionlayout.ListReportsFragment.onActivityCreated(ListReportsFragment.java:58)
答案 0 :(得分:0)
您正在创建MainActivity的新对象,这就是您收到错误的原因
c(0,1)+which.max(diff(time(z))) # 12,13
将MainActivity传递给片段,然后将其传递给ListAdapter
adapter = new ListAdapter(new MainActivity());
答案 1 :(得分:0)
更改
adapter = new ListAdapter(new MainActivity());
到
adapter = new ListAdapter(getActivity());
答案 2 :(得分:0)
从
改变adapter = new ListAdapter(new MainActivity());
到
adapter = new ListAdapter(getActivity());
另外,将这部分代码移动到onCreateView(),如下所示:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
adapter = new ListAdapter(getActivity());
listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//what to do on item click goes here!
});
return rootView;
}