Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - retrieve string array from resources

Below is the code that i made to retrieve the string array item:

String[] menuArray;  @Override public void onCreate(Bundle savedInstanceState)  {            super.onCreate(savedInstanceState);     setContentView(R.layout.main);      ScrollView sv = new ScrollView(this);     LinearLayout ll = new LinearLayout(this);     ll.setOrientation(LinearLayout.VERTICAL);     sv.addView(ll);   // Create an ArrayAdapter that will contain all list items     ArrayAdapter<String> adapter;      menuArray = getResources().getStringArray(R.array.menu);        for(int i = 0; i < menuArray.length; i++)      {         Button b = new Button(this);         b.setText(menuArray[i]);         ll.addView(b);     }      this.setContentView(sv);  } 

This is the strings.xml file:

 <string-array name="menu">         <item>1</item>         <item>2</item>         <item>3</item>         </string-array> 

However, the R.array.menu having this issue to compile: As of ADT 14, resource fields cannot be used as switch cases. Invoke this fix to get more information.

like image 260
Yuen Tong Avatar asked May 10 '12 11:05

Yuen Tong


People also ask

How do you get string from resources?

android:text="@string/hello" /> String string = getString (R. string. hello); You can use either getString(int) or getText(int) to retrieve a string.

How do I get string array in Kotlin?

Kotlin has set() and get() functions that can directly modify and access the particular element of the array respectively. In Kotlin Array, the get() function is used to get the elements from the specified index. The set() function is used to set element at particular index location.

What is string resource in Android?

A string resource provides text strings for your application with optional text styling and formatting. There are three types of resources that can provide your application with strings: String. XML resource that provides a single string. String Array.


1 Answers

How to retrieve a string array from resources:

array.xml

<?xml version="1.0" encoding="utf-8"?> <resources>      <string-array name="my_string_array">         <item>one</item>         <item>two</item>         <item>three</item>     </string-array>  </resources> 

Code

String[] stringArray = getResources().getStringArray(R.array.my_string_array); 

(The OP already had their question answered but based on the question title, other people may come here looking for this answer.)

like image 141
Suragch Avatar answered Oct 22 '22 23:10

Suragch