Cannot resolve "array" in R.array.items (android studio)

Viewed 999

I know many questions like this one already exist, but I looked through them and couldn't find an answer.

For some reason the keyword "array" is underlined in red, and I am getting the error: Cannot resolve "array". I have built the project, checked my xml file, but I just cannot figure out what is wrong.

package com.example.listapp;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    ListView myListView;
    String[] fruits;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Resources res = getResources();
        myListView = (ListView)findViewById(R.id.my_list_view);
        fruits = res.getStringArray(R.array.items);
    }
}

Also here is my strings.xml file (under res/values/strings.xml):

<resources>
    <string name="app_name">List App</string>

    <string-array name="items">
        <item>peach</item>
        <item>apple</item>
        <item>banana</item>
    </string-array>

    <string-array name="prices">
        <item>$1.49</item>
        <item>$0.99</item>
        <item>$0.89</item>
    </string-array>

    <string-array name="descriptions">
        <item>Fresh peaches from Georgia</item>
        <item>Fresh apples from Ohio</item>
        <item>Fresh bananas from California</item>
    </string-array>
</resources>

The line with the error is:

fruits = res.getStringArray(R.array.items);

enter image description here

4 Answers

Replace res to getResources()

Try like this:

final String[] values = getResources().getStringArray(R.array.items);

Clean and Re-Build your projct or Invalid Crashes/ Restart

 <array name="select_city">
        <item>Surat</item>
        <item>Ahmedabad</item>
        <item>Vadodara</item>
        <item>Anand</item>
        <item>Amreli</item>
        <item>Rajkot</item>
    </array>

then use like this

 String [] abc=getResources().getStringArray(R.array.select_city);
String[] values = getResources().getStringArray(R.array.items);

This will be work, If u still getting error, please Build->Clean Project or File->Invalid Crashes/ Restart

I think it will solve your problem

The main reason behind this error is you have no array.xml file in values folder your are created string-array in string.xml

Solution:

Create the array.xml file in values folder and copy & past all string-array to array.xml

enter image description here

Related