2

How do I insert a string on an array from the strings.xml file, if I enter the following error I get the error getText(R.string.home)

Error: Cannot resolve method 'getText(int)'

static String[] titles ={"Home",
        "Profile",
        "Settings",
        "Exit"};

4 Answers 4

2

You will need a Context object in order to be able to call the getString() method. The reason you can often write simply getString(R.string.foo) rather than something like mContext.getString(R.string.foo) is that the Activity class is a subclass of Context.

How exactly you get a Context object will depend on where you're trying to execute this code. In a Fragment, you can write getActivity().getString(R.string.foo).

Sign up to request clarification or add additional context in comments.

Comments

1

Use getString() method as follows:

static String[] titles ={getString(R.string.home),
        getString(R.string.profile),
        getString(R.string.settings),
        getString(R.string.exit)};

If you are not calling this in an Activity but in a fragment, you must use getActivity().getString. Hope that helps.

1 Comment

NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
1

you can try in this way

 <string-array name="home">
    <item>Home</item>
    <item>Profile</item>
    <item>Settings</item>
    <item>Exit</item>
</string-array>

String [] titles= getResources().getStringArray(R.array.home);

Comments

0

put you string array in like this on strings.xml file

<string-array name="menuItems">
        <item>Home</item>
        <item>Profile</item>
        <item>Settings</item>
        <item>Exit</item>
    </string-array>

Access in your java file like this

String [] fruitsArray= getResources().getStringArray(R.array.menuItems);

Comments

Your Answer

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.