Android generate xml elements based on array - android

In WPF we can define an array and bind it to our xml. Elements are then automatically generated based on the contents of this array.:
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
this.DataContext = this;
}
ObservableCollection<int> sampleData = new ObservableCollection<int>();
public ObservableCollection<int> SampleData {
get {
if (sampleData.Count <= 0) {
sampleData.Add(1);
sampleData.Add(2);
sampleData.Add(3);
sampleData.Add(4);
}
return sampleData;
}
}
}
<Window x:Class="Sandbox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox ItemsSource="{Binding Path=SampleData}"/>
</Grid>
</Window>
Is something like this possible in android?

You can define an XML file, in res/values/strings.xml, to define your array member using:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="planets_array">
<item>Mercury</item>
<item>Venus</item>
<item>Earth</item>
<item>Mars</item>
</string-array>
</resources>
More about array resource
Then receive using
getResources().getStringArray(R.array.planets_array);
But there is no
automatically generated based on the contents of this array
similar method in Android. To do it you will need to implement an ArrayAdapter.
More about ArrayAdapter

Related

Selecting a specific string array

I have a question and i cant find a solution myself. I am using for example the following string arrays:
<string-array name="alphabet">
<item>ccc</item>
<item>bbb</item>
<item>aaa</item>
</string-array>
<string-array name="ccc">
<item>1</item>
<item>2</item>
<item>3</item>
</string-array>
<string-array name="bbb">
<item>4</item>
<item>5</item>
<item>6</item>
</string-array>
<string-array name="aaa">
<item>7</item>
<item>8</item>
<item>9</item>
</string-array>
So, The first string array alphabet is placed inside a spinner. (dropdown menu) Lets say i select CCC, Then i want only the items in between the array CCC to be worked with and stored in an array These information in this array should then be randomized and formatted into groups later on. But i only need a selection of the string selected.
So is there a way to select just one array based on the choice made out of the first array?
Kind regards,
Here is the code, the way you needed.
Step 1] Set, setOnItemSelectedListener on first spinner and get the Arrayname for target spinner
spinner_alphabates.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
{
String arrayName = spinner_alphabates.getSelectedItem().toString();
int resId = getResources().getIdentifier(arrayName,"array",getPackageName());
setResultArray(resId);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Step 2] set the result array on target spinner as
public void setResultArray(int resID)
{
String [] result_array = getResources().getStringArray(resID);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, result_array);
spinner_result.setAdapter(adapter);
}
No need to put 'if' 'else' conditions to match array names.
Hope this help you.
Try this, I am not sure whether it is going to work, just have try
<string-array name="ccc">
<item>1</item>
<item>2</item>
<item>3</item>
</string-array>
<integer-array name="id">
<item> #array/ccc </item>
</integer-array>
You need to get array of string like this. and you will access it with index of string array.
String.xml
<string-array name="my_books">
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
<item>Item 4</item>
</string-array>
Get List of string in Java file like :
Resources res = getResources();
String[] myBooks = res.getStringArray(R.array.my_books);
Try this method and put this method into onCreate in activity method..
change this array add one more item..
<string-array name="alphabet">
<item>Select</item>
<item>ccc</item>
<item>bbb</item>
<item>aaa</item>
</string-array>
private void initView() {
spinner = findViewById(R.id.spinner);
final List<String> asList = Arrays.asList(getResources().getStringArray(R.array.alphabet));
final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, asList);
final ArrayAdapter<String> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (spinner.getSelectedItem().equals("ccc")) {
adapter2.addAll(Arrays.asList(getResources().getStringArray(R.array.ccc)));
spinner.setAdapter(adapter2);
adapter2.notifyDataSetChanged();
} else if (spinner.getSelectedItem().equals("aaa")) {
adapter2.addAll(Arrays.asList(getResources().getStringArray(R.array.aaa)));
spinner.setAdapter(adapter2);
adapter2.notifyDataSetChanged();
} else if (spinner.getSelectedItem().equals("bbb")) {
adapter2.addAll(Arrays.asList(getResources().getStringArray(R.array.bbb)));
spinner.setAdapter(adapter2);
adapter2.notifyDataSetChanged();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}

Populate ListView with text and value from strings.xml

I'm new to android and want to populate listview items that have id as value and string as caption.
All I could find searching was that they suggest using string array like:
<string-array name="test">
<item>first item</item>
<item>second item</item>
</string-array>
What i'm looking for is something like:
<string-array name="test">
<item value="1">first item</item>
<item value="2">second item</item>
</string-array>
just like the option tags of a select in html
Create a new Activity (this will make a xml file (layout) and a Java class.
On the layout, create a Layot that has a ListView on int:
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical” >
<ListView
android:id=”#+id/itemList”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:entries="#array/test"
/>
On your activity, you have to:
Create a ListView variable
Map your view on the XML on this variable
Get a list of Strings from your resource array-adapter
Instanciate an Adapter (an object that you have to set on your listview to get your list (in your case, of strings) and add them in your recycler view. You can create a customized class for your adapter it, but when dealing with Strings, you can use a simple one called ArrayAdapter).
Set your adapter on your ListView object
To do all of those things, you put this in your code:
public class MyActivity extends Activity {
// Creating variable
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Mapping with your XML view
listView = (ListView) findViewById(R.id.itemList);
/// Getting list of Strings from your resource
String[] testArray = getResources().getStringArray(R.array.test);
List<String> testList = Arrays.asList(test);
// Instanciating Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<>(getBaseContext(),
android.R.layout.simple_list_item_1, testList);
// setting adapter on listview
listview.setAdapter(adapter);
}
}
This will help you to retrieve string by position..
String[] some_array = getResources().getStringArray(R.array.your_string_array)

Retrieving the bound value of a spinner

I want to get Selected Value of a spinner.
First, I created a STRING-ARRAY in res/values/string
<string-array name="location">
<item name="AUH">ABU DHABI</item>
<item name="AAN">AL AIN</item>
<item name="DMM">DAMMAM</item>
</string-array>
Spinner Definition in Layout:
<Spinner
android:id="#+id/spnOrigin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="#array/location"/>
Now I need to complete the button click body, if user selects ABU DHABHI, he should return AUH.
GETSELECTITEM returns ABU DHABI, not the value behind this. If I try something like this, can this approach allow me to get NAME attribute?
String[] _location =getResources().getStringArray(R.array.location);
Button Handler:
bttProcess.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
});
I don't believe the name attribute is valid on items of a string array.
I think your best bet is to set up another array to have the values in it. You can do ((AdapterView)getViewById(R.id.spnOrigin)).getSelectedItemPosition() then look up the relevant name from that other array.
Try to follow the exemple in the android developer website to get started using spinner
First your activity have to implement AdapterView.OnItemSelectedListener. This will provide a callback method that will notify your application when an item has been selected from the Spinner.
public class SpinnerActivity extends Activity implements OnItemSelectedListener
Second you need to register for the interface implementation by calling:
spinner.setOnItemSelectedListener(this);
Finally within "onItemSelected" method of that class, you can get the selected item:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selected = parent.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
use your string array like this
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="locations">
<item>ABU DHABI</item>
<item>AL AIN</item>
<item>DAMMAM</item>
</string-array>
</resources>
In this scenario where Spinner need to bind by KEY - VALUE PAIR List,
The spinner can be get values from
1. DATABASE
2. An static String Array.
3. By creating Bi- Resource String Array.
FOR 3rd Point:
If you need to bind spinner by resource String Array, u need to create two array. One which will hold KEY [NAMES Of Countries], Second Will contains VALUES [Short Code of Countries].
Than on Click Button,
bttProcess.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int position = spinner.getSelectedItemPosition();
Log.i("Code:","Selected Country Code: "+
getStringFromArray(R.array.locations_code, position ));
});
private String getStringFromArray(int id, int index) {
try {
String[] bases = getResources().getStringArray(id);
return bases[index];
}
catch (Exception e) {
return "";
}
}
RESOURCES would look like,
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="locations">
<item>ABU DHABI</item>
<item>AL AIN</item>
<item>DAMMAM</item>
</string-array>
<string-array name="locations_code">
<item>ABU</item>
<item>AL</item>
<item>DAM</item>
</string-array>
</resources>

how to read particular key value in string.xml on android?

string.xml contains lot of keys with value. I want to get particular value based on key.
For example, string.xml contains key1, key2 up to key100. I displaying these keys into ListView. If user select the key50 means I want to displaying the corresponding value in TextView. How to achieve this?
Sample string.xml file,
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<resources>
<string name="key1">value 1</string>
<string name="key2"> value 2 </string>
...
...
<string name="key100"> value 100 </string>
</resources>
You should save your key as a string array resource like this
<string-array name="my_keys">
<item>Key 1</item>
<item>Key 2</item>
<item>Key 3</item>
<item>Key 4</item>
<item>Key 5</item>
<item>Key 6</item>
</string-array>
Populate the listView with the following code.
String[] myKeys = getResources().getStringArray(R.array.my_keys);
ListView mListView = (ListView)findViewById(R.id.yourListView);
mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myKeys));
Retrieve the clicked item and put the value into the TextView
TextView myTextView = (TextView)findViewById(R.id.yourTextView);
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
myTextView = ((TextView) view).getText();
}
});
If you have a <string name="key">string value</string> resources then the only way is to access them by key:
String value = context.getString(R.string.key);
Btw, if you need to store some arbitrary data into your Views (the ones inside your ListView), use view.setTag(object) and view.getTag().
I will suggest to use XPath to get your value for keys.

Populating spinner directly in the layout xml

Is it possible to populate the options of a Spinner right in the layout xml? This page suggests I should use an ArrayAdapter? It seems awkward not being able to do it..
I'm not sure about this, but give it a shot.
In your strings.xml define:
<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>
In your layout:
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
android:entries="#array/array_name"
/>
I've heard this doesn't always work on the designer, but it compiles fine.
Define this in your String.xml file and name the array what you want, such as "Weight"
<string-array name="Weight">
<item>Kg</item>
<item>Gram</item>
<item>Tons</item>
</string-array>
and this code in your layout.xml
<Spinner
android:id="#+id/fromspin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="#array/Weight"
/>
In your java file, getActivity is used in fragment; if you write that code in activity, then remove getActivity.
a = (Spinner) findViewById(R.id.fromspin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.weight, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
a.setAdapter(adapter);
a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (a.getSelectedItem().toString().trim().equals("Kilogram")) {
if (!b.getText().toString().isEmpty()) {
float value1 = Float.parseFloat(b.getText().toString());
float kg = value1;
c.setText(Float.toString(kg));
float gram = value1 * 1000;
d.setText(Float.toString(gram));
float carat = value1 * 5000;
e.setText(Float.toString(carat));
float ton = value1 / 908;
f.setText(Float.toString(ton));
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
// Inflate the layout for this fragment
return v;
}
In regards to the first comment: If you do this you will get an error(in Android Studio). This is in regards to it being out of the Android namespace. If you don't know how to fix this error, check the example out below. Hope this helps!
Example -Before :
<string-array name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
Example - After:
<string-array android:name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>

Categories

Resources