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.
The second approach is more complicated and adds no value over the first approach. Use the first approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With