how to initialize a string [] with a string-array of Android resources?

2

That wave friends, I would like to know about the question, what happens is that I have this:

String[] data = {"Ejemplo 1", "Ejemplo 2", "Ejemplo 3", "Ejemplo 4"};

and I have this string arrangement in my resources:

<string-array
name="ejemplos">
    <item>Ejemplo 1</item>
    <item>Ejemplo 2</item>
    <item>Ejemplo 3</item>
    <item>Ejemplo 4</item>
</string-array>

I would like to initialize or equalize the "examples" of resources in the data variable.

I'm trying this way but it throws me an exception

private String[] data = getResources().getStringArray(R.array.ejemplos);

and this is the error

  

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

I hope you answer, thank you in advance

    
asked by Luis García 02.05.2017 в 23:22
source

2 answers

2

Assuming that your array is in the right place, in resources.

You can not access it before the resources have been loaded.

If you proceed like this it should work:

   public class MainActivity extends Activity {


    String[] data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tulayout);
        //Aquí los recursos han sido cargados, entonces puedes invocar el array

        data = getResources().getStringArray(R.array.ejemplos); 
        System.out.println (data);   

    }

    @Override
    protected void onResume() {
        super.onResume();
        //...
    }


  }
    
answered by 02.05.2017 / 23:43
source
1

You are getting this error because access to resources requires the context:

  

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

which can not be obtained by defining the obtained values of the array.

private String[] data = getResources().getStringArray(R.array.ejemplos);

To solve this, you must first define the variable of the array:

private String[] data;

and then get the data, remember that you require the context, but if you are in an Activity you can simply get them in this way:

data = getResources().getStringArray(R.array.ejemplos);
    
answered by 03.05.2017 в 02:47