I tried reading a number of solutions on Stack Overflow and have found they either don't work for my scenario or I simply don't understand their explanation (I am very new to Java and Android. I have strings set up under res/values/strings.xml that I wish to use in the class:-
public class AttractionFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.word_list, container, false);
// create an array list of details
final ArrayList<Details> details = new ArrayList<>();
// Details details
details.add(new Details(getActivity().getString(R.string.fun_bigsplash_name), getString(R.string.fun_bigsplash_addr), R.string.fun_bigsplash_num, R.drawable.bigsplash));
I've tried a number of variants (the reason they are different is just to show what I tried) but can't work it out. The R.drawable.bigsplash works fine (when I'm using literal strings for the others).
The error message states an int, which I assume means it's getting the reference and not the actual string.
How do I get the string from within the fragment?
Thanks.
You can use:
getResources().getString(R.string.my_string);
or just:
getString(R.string.my_string);
Read String value or String Array In Java Code.
Define a string array in strings.xml use string-array xml element.
Show Selection
<string name="auto_complete_text_view_car">Input Favorite Car Name</string>
<string-array name="car_array">
<item>Audi</item>
<item>BMW</item>
<item>Benz</item>
<item>Ford</item>
<item>Toyota</item>
<item>Tesla</item>
<item>Honda</item>
<item>Hyundai</item>
</string-array>
Read String Value In Java Code. Only string name
Inside Activity::
String defaultInputText = getResources().getString(R.string.auto_complete_text_view_car);
Inside Fragment::
String defaultInputText = getActivity().getResources().getString(R.string.auto_complete_text_view_car);
Inside Activity::
String carArr[] = getResources().getStringArray(R.array.car_array);
Inside Fragment::
String carArr[] = getActivity().getResources().getStringArray(R.array.car_array);
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