-1

I've got a problem with a simple tutorial code i've follow to learn Recyclerview. First I create a class to represent item like :

package tom_d.fr.testrecyclerview;

import android.content.res.Resources;
import java.util.ArrayList;

public class Planete {

    public String mNom;
    public int mDistance;
    protected ArrayList<Planete> mListe;

    Planete(String nom, int distance) {
        mNom = nom; // nom de la planète
        mDistance = distance; // distance au soleil en Gm

        Resources res = getResources();
        final String[] noms = res.getStringArray(R.array.noms);
        final int[] distances = res.getIntArray(R.array.distances);

        mListe = new ArrayList<Planete>();
        for (int i=0; i<noms.length; ++i) {
            mListe.add(new Planete(noms[i], distances[i]));
        }
    }

I get error: cannot find symbol method getResources()

Even if I try with :

Resources res = getApplicationContext().getResources();

How to proceed ? I just want to acess to an xml file with arrays :(

I've also search for this error here on stackoverflow and other website but no functionnal answer....

I think I've made a mistake but I don't know where :/

Tom Detranchant
  • 71
  • 1
  • 1
  • 7

3 Answers3

2

You need a context to access resource. Pass a context from your activity to your class

Planete(Context context, String nom, int distance) {
    Resources res = context.getResources();
}

Then in your activity

new Planete(this, "sample", 1);
Android_K.Doe
  • 753
  • 1
  • 4
  • 11
0

transform your class like this

public class Planete {

    private Context context;
    public String mNom;
    public int mDistance;
    protected ArrayList<Planete> mListe;

    Planete(Context context, String nom, int distance) {
        mNom = nom; // nom de la planète
        mDistance = distance; // distance au soleil en Gm

        Resources res = context.getResources();
        final String[] noms = res.getStringArray(R.array.noms);
        final int[] distances = res.getIntArray(R.array.distances);

        mListe = new ArrayList<Planete>();
        for (int i=0; i<noms.length; ++i) {
            mListe.add(new Planete(noms[i], distances[i]));
        }
    }
}

this will work

Harkal
  • 1,770
  • 12
  • 28
0

You can not use "resources" directly, Because this is the external class file. And where this external class file is used, it is not known.

If you use getAplicationContext() then it still does not allow access to resources.

Therefore you can use project resources with context to those activity where it calls or uses.

Planete(Context context, String nom, int distance) {
    Resources res = context.getResources();
}
Prince Dholakiya
  • 3,255
  • 27
  • 43