[英]Fragment BaseAdapter returns a NullPointerException
My app consists of two Fragments
that need to get information from the MainActivity
. 我的应用程序包含两个
Fragments
,需要从MainActivity
获取信息。 In the MainActivity
the data is loaded and put into ArrayLists
, then it should be presented in the first Fragment
. 在
MainActivity
将数据加载并放入ArrayLists
,然后将其显示在第一个Fragment
。 So I created a method that passes the ArrayLists
to the first Fragment
. 因此,我创建了一个将
ArrayLists
传递给第一个Fragment
。
The issue I came across is that I get a NullPointerException
on the mContactsAdapter = new SimpleAdapter(...)
line in my Fragment
class. 我遇到的问题是,我的
Fragment
类中的mContactsAdapter = new SimpleAdapter(...)
行上出现NullPointerException
。 But I don't understand why that is, since I set up the Adapter
in the onCreateView
method. 但是我不明白为什么会这样,因为我在
onCreateView
方法中设置了Adapter
。 Is it set up a wrong way? 设置错误吗?
My MainActivity: 我的主要活动:
public class MainActivity extends AppCompatActivity {
ArrayList<HashMap<String, String>> contactList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
}
public void FillAndPresent() {
/***
* fill ArrayLists
* ...
*/
CallsFragment fragment = new CallsFragment();
((CallsFragment) fragment).show(contactList);
}
}
My Fragment class: 我的片段类:
public class CallsFragment extends Fragment{
private BaseAdapter mContactsAdapter;
private final List<HashMap<String, String>> mContactsListItems = new ArrayList<>();
public CallsFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_calls, container, false);
((ListView) view.findViewById(R.id.list))
.setAdapter(mContactsAdapter);
return view;
}
public void show(ArrayList c){
mContactsAdapter = new SimpleAdapter(
getActivity(), mContactsListItems,
R.layout.list_item, new String[]{"price", "brand",
"dist"}, new int[]{R.id.price,
R.id.brand, R.id.dist});
mContactsListItems.addAll(c);
mContactsAdapter.notifyDataSetChanged();
((ListView) getActivity().findViewById(R.id.list))
.setAdapter(mContactsAdapter);
}
}
As @0x0nosugar said 如@ 0x0nosugar所说
This is happening because the Fragment is not yet attached to the Activity"
发生这种情况是因为片段尚未附加到活动中”
try this 尝试这个
CallsFragment fragment = new CallsFragment();
fragment.show(contactList);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.mainActivity,fragment);
// >> here you replace the main activity layout with your fragment by put the id of it.
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.