Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the right way to get string resources from within a Fragment?

Tags:

Which method is generally better / safer for reading string resources while in a Fragment?

Here I read getResources().getString() directly:

public class SomeFragment extends Fragment {

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = getResources().getString(R.string.my_string_id);
    }

}

Or is it better to do it this way, by setting a Context field first and then reading the resources from that:

public class SomeFragment extends Fragment {
    private Context context;

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = context.getResources().getString(R.string.my_string_id);
    }

}

Any tradeoffs/drawbacks to either of these methods?

The reason I ask is because sometimes I've run into nullpointer issues with the first approach that were resolved by using the second approach; so I wasn't sure if it was problematic to use the first one.

like image 824
KaliMa Avatar asked Jul 06 '17 14:07

KaliMa


1 Answers

The second approach is more complicated and adds no value over the first approach. Use the first approach.

like image 143
CommonsWare Avatar answered Oct 04 '22 16:10

CommonsWare