My app consists of two Fragments
that need to get information from the MainActivity
. In the MainActivity
the data is loaded and put into ArrayLists
, then it should be presented in the first Fragment
. So I created a method that passes the ArrayLists
to the first Fragment
.
The issue I came across is that I get a NullPointerException
on the mContactsAdapter = new SimpleAdapter(...)
line in my Fragment
class. But I don't understand why that is, since I set up the Adapter
in the onCreateView
method. 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
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();
read more about fragment here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.