简单的json解析,但是无论何时我想要构建它,我都无法做到,它崩溃了,我认为是因为“ findViewById”。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    showDrugs(null);
    return inflater.inflate(R.layout.fragment_first, container, false);
}
private void showDrugs(String search) {
    ListView lvDrugs = (ListView) getView().findViewById(R.id.lvDrugs);
    MyRealm myRealm = new MyRealm(getActivity().getApplicationContext());
    RealmResults<Drug> drugs = myRealm.getDrugs(search);
    DrugListAdapter adapter = new DrugListAdapter(getActivity().getApplicationContext(), drugs);
    lvDrugs.setAdapter(adapter);
}

最佳答案

在扩展视图之前,不能调用showDrugs(),因为getView()null

最简单的方法是在showDrugs()中调用onViewCreated(),在onCreateView()之后立即调用它,您可以确定getView()不是null

08-18 17:17