views:

1556

answers:

1

I am just trying to display a list from an array that I have in my arrays.xml. When I try to run it in the emulator, I get a force close message.

If I define the array in the java file (String[] testArray = "one","two","three","etc";) it works, but when I use "String[] testArray = getResources().getStringArray(R.array.testArray); " it doesnt work.

Here is my Java file:

package com.xtensivearts.episode.seven;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class Episode7 extends ListActivity {
 String[] testArray = getResources().getStringArray(R.array.testArray);

 /** Called when the activity is first created. */
 @Override
 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  // Create an ArrayAdapter that will contain all list items
  ArrayAdapter<String> adapter;

  /* Assign the name array to that adapter and 
     also choose a simple layout for the list items */ 
  adapter = new ArrayAdapter<String>(
    this,
    android.R.layout.simple_list_item_1,
    testArray);

  // Assign the adapter to this ListActivity
  setListAdapter(adapter);
 }


}

Here is my arrays.xml file




first
second
third
fourth
fifth

+1  A: 

You can't initialize your testArray field this way, because the application resources still aren't ready.

Just change the code to:

package com.xtensivearts.episode.seven;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class Episode7 extends ListActivity {
String[] mTestArray;

/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // Create an ArrayAdapter that will contain all list items
    ArrayAdapter<String> adapter;

    mTestArray =  = getResources().getStringArray(R.array.testArray);    

    /* Assign the name array to that adapter and 
    also choose a simple layout for the list items */ 
    adapter = new ArrayAdapter<String>(
    this,
    android.R.layout.simple_list_item_1,
    mTestArray);

    // Assign the adapter to this ListActivity
    setListAdapter(adapter);
    }
}
Dimitar Dimitrov
That did it! Thank you very much for your help and your explanation. Being a beginner I need the explanations!
Soren