3
\$\begingroup\$

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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Nov 23, 2016 at 12:29
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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.

answered Nov 23, 2016 at 13:06
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.