Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get string from resources strings into a fragment

Tags:

android

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.

like image 470
Markus Avatar asked Dec 17 '18 08:12

Markus


2 Answers

You can use:

getResources().getString(R.string.my_string);

or just:

getString(R.string.my_string);
like image 176
Anton Sarmatin Avatar answered Nov 03 '22 23:11

Anton Sarmatin


Read String value or String Array In Java Code.

  1. 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>
    

  2. 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);
  1. Read the string array in java source code. Please note car_array is just the string array name defined in strings.xml.

Inside Activity::

String carArr[] = getResources().getStringArray(R.array.car_array);

Inside Fragment::

String carArr[] = getActivity().getResources().getStringArray(R.array.car_array);
like image 37
King of Masses Avatar answered Nov 03 '22 22:11

King of Masses