This phonebook application has a menu, which sorts by name or category. I do it like this in MainActivity
:
Bundle bundle = new Bundle();
Fragment lvFragSortBy = new ListViewFragment();
switch (item.getItemId()) {
case R.id.menuSortOrderName:
item.setChecked(true);
bundle.putString("sortBy", "name");
lvFragSortBy.setArguments(bundle);
getFragmentManager()
.beginTransaction()
.replace(R.id.fragContainer, lvFragSortBy)
.commit();
return true;
case R.id.menuSortOrderCategory:
item.setChecked(true);
bundle.putString("sortBy", "category");
lvFragSortBy.setArguments(bundle);
getFragmentManager()
.beginTransaction()
.replace(R.id.fragContainer, lvFragSortBy)
.commit();
return true;
In ListViewFragment
:
Bundle sortBundle = getArguments();
if (sortBundle != null) {
orderBy = sortBundle.getString("sortBy");
}
And then:
protected ArrayList<Contact> doInBackground(Void... params) {
try {
db = new DbWorker(ctx);
contacts = (ArrayList<Contact>) db.selectAllContacts(orderBy);
} catch (Exception e) {
Log.e(TAG, "Exception in AsyncTask.doInBackground");
}
return contacts;
}
This code works fine but I would like to know if it can be done better.
1 Answer 1
You should use newInstance() pattern, described in this link
The profit of using this pattern is, developer cannot instantiate Fragment
without providing arguments. There will be no chances that you will get default value when you try to get that value. One more thing is, whatever key is required for a fragment should be defined in public static final String
so that no chances for string mismatch in key.