spinner key and value - android

I am creating a translater app in which user need to choose the target language if suppose he choose marathi from the spinner then value for the marathi should be 'mr' so i can pass that value in url.
I have created a spinner and assigned languages from strings.xml but I want to use it's short form like for hindi the value should be hi, how can I achieve that?
<string-array name="languages">
<item>Marathi</item>
<item>Hindi</item>
<item>Japanese</item>
<item>Russian</item>
<item>Bengali</item>
<item>Greek</item>
<item>Gujarati</item>
<item>Italian</item>
<item>Malayalam</item>
<item>German</item>
<item>Punjabi</item>
<item>Tamil</item>
<item>Telugu</item>
<item>French</item>
<item>Urdu</item>
</string-array>

I would go for map instead.
1-create the languages map
Map<String, String> languages = new HashMap<>();
languages.put("hindi", "hi");
languages.put("arabic", "ar");
languages.put("english", "en");
2-get the selected item
String selectedLanguage = mySpinner.getSelectedItem().toString();
String languageToSend=languages.get(selectedLanguage); //send it to url

You can create a Map object for your above functionality. You can create something like this.
Map<String, String> map = new HashMap<String, String>();
map.put("Hindi", "Hi");
map.put("Marathi", "Mi");
You can reverse the order of the key and value according to your need. For populating your spinner you can get all the keys and put in a list and then add it to your spinner. You can do it like this
List<String> l = new ArrayList<String>(map.keySet());

One way to achieve that is by using Map as suggested by #Vivek Mishra (in comments) where key will be your language name to be displayed in spinner and value will be the language code you want to pass in URL.
Map will look something like below
languageMap.put ("Marathi","mr");
languageMap.put ("Hindi","hi");
Now when you want to use, get the String from the spinner, selected by User and get language code value by
languageMap.get("Marathi")
Another option to integrate with your current implementation, is to add language code array in String.xml in same order as language name array and get the same index from language code array as per the selected index of spinner.
<string-array name="languages_code">
<item>mr</item>
<item>hi</item>
<!-- Add entries for other languages -->
</string-array>

you can create tow list like
List fullname= new ArrayList();
fullname.add("hindia");
fullname.add("persian");
fullname.add("english");
List urlName= new ArrayList();
urlName.add("hin");
urlName.add("per");
urlName.add("eng");
then add first one to spiner
ArrayAdapter dataAdapter = new ArrayAdapter(context, R.layout.spinner_dropdown, fullname);
// Drop down layout style - list view with radio button
// dataAdapter.setDropDownViewResource(R.layout.spinner_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
finally with implements AdapterView.OnItemSelectedListener and andspinner.setOnItemSelectedListener(this);
to get equivalent value use below code:
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i,
long l) {
String url=urlName.get(i);
}

You can add one string array with short names corresponding to languages array you already have, and fetched short language name by using position in "onItemSelected".
Following is a simplest way to achieve desired output:
Strings.xml
<string-array name="languages">
<item name="">Marathi</item>
<item>Hindi</item>
<item>Japanese</item>
<item>Russian</item>
<item>Bengali</item>
<item>Greek</item>
<item>Gujarati</item>
<item>Italian</item>
<item>Malayalam</item>
<item>German</item>
<item>Punjabi</item>
<item>Tamil</item>
<item>Telugu</item>
<item>French</item>
<item>Urdu</item>
</string-array>
<string-array name="sr_languages">
<item name="">Ma</item>
<item>Hi</item>
<item>Ja</item>
<item>Ru</item>
<item>Be</item>
<item>Gr</item>
<item>Gu</item>
<item>It</item>
<item>Ma</item>
<item>Ge</item>
<item>Pu</item>
<item>Ta</item>
<item>Te</item>
<item>Fr</item>
<item>Ur</item>
</string-array>
SpinnerActivity.java
package com.example.sonias.stackoverflowdemos;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
public class SpinnerActivity extends AppCompatActivity {
private Spinner spLanguage;
private ArrayAdapter<String> spAdapter;
private String mSelectedLanguage = "";
private ArrayList<String> LanguagesList;
private ArrayList<String> srLanguagesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner);
spLanguage = (Spinner) findViewById(R.id.spLanguage);
LanguagesList = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.languages)));
srLanguagesList = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.sr_languages)));
spAdapter = new ArrayAdapter<>(SpinnerActivity.this, android.R.layout.simple_list_item_1, LanguagesList);
spLanguage.setAdapter(spAdapter);
spLanguage.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String mSelectedTExt = ((TextView) view.findViewById(android.R.id.text1)).getText().toString();
mSelectedLanguage = srLanguagesList.get(position);
Toast.makeText(SpinnerActivity.this, "You have selected " + mSelectedTExt + " ( " + mSelectedLanguage + " )", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}

Related

How to save selection id's from listview

I have an activity that contains a submit button and a multiple select listview that I populate with a string-array, this array exists in both english and french.
strings.xml
<string-array name="trucks">
<item name="truck1">Mini-van</item>
<item name="truck2">Pick-up</item>
<item name="truck3">4 x 4</item>
</string-array>
strings_fr.xml
<string-array name="trucks">
<item name="truck1">Mini-van french</item>
<item name="truck2">Pick-up french</item>
<item name="truck3">4 x 4 french</item>
</string-array>
Once the user selects which ever items he/she wants they hit a button to save the selections(locally to an array). I am able to get the string content of the selected items but if i save those then it would be saving the language specific values. what I need is the name or some sort of id (truck1, truck2) to save so that the next time the list is loaded I can pragmatically check off the saved list items regardless of language, as well as send the vehicle id's to the server when it comes time to permanently save the data.
Below is what I have so far..
activity_truck_picker.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/btn_truck_done"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="#style/themedButton"
android:layout_alignParentBottom="true"
android:text="Add Truck(s)" />
<ListView
android:id="#+id/lst_trucks"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/btn_truck_done"
android:layout_alignParentTop="true"
/>
</RelativeLayout>
TruckPickerActivity.java
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class TruckPickerActivity extends Activity implements
View.OnClickListener {
private static final String TAG = "Presite";
Button button;
ListView listView;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_truck_picker);
listView = (ListView) findViewById(R.id.lst_trucks);
button = (Button) findViewById(R.id.btn_truck_done);
String[] trucks = getResources().getStringArray(R.array.trucks);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, trucks);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
button.setOnClickListener(this);
}
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
}
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
Log.i(TAG, "Truck Selected: " + selectedItems.get(i));
String itemName = ...; // Some how look up name of string in array for storing in database
}
}
}
I cant figure out a way to get the names/id of the selected options for saving.
Any help would be appreciated.
You can add an onItemClickListener to your ListView, where the long id parameter is the id of the item that has been clicked:
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//Do something with id parameter
}
});
If I understand you correctly, you'd like to get the name attribute of your string array declared in xml. I'd create a 2nd array holding the name of your 1st array, and fetch the names using the id or position parameter from onItemClickListener()

How to assign Integer Value to variable based on ITEM selected on the Android Spinner.?

I have set a Array Adapter for my Spinner to display a drop-down list of Grades (A+, A, ...etc).
All I need is when the user selects, A+, myApp should understand it as float value 10, so that the Value of A+ (=10) can be used in Formula that needs integer to calculate the overall grade.
for eg, if user select B+, my APP should understand as 8.5, which can be used in the formula.
Basically, I want the USERS to see the Grades on the spinners but I need the Actual values of it for Calculation.
Can I make use of POSITION of Items on the Spinners?
Kindly show an example how to retrieve it.
My String resource:
<?xml version="1.0" encoding="utf-8"?>
<resources>
</string-array>
<string-array name="grade_list">
<item>A+</item>
<item>A</item>
<item>A-</item>
<item>B+</item>
<item>B</item>
<item>B-</item>
<item>C+</item>
<item>C</item>
<item>C-</item>
<item>D</item>
<item>E</item>
<item>U</item>
</resources>
MY JAVA CODE
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class CSEsem1 extends Activity implements OnClickListener{
Spinner cs1spin1;
Spinner cs1spin2;
Spinner cs1spin3;
Spinner cs1spin4;
Spinner cs1spin5;
Spinner cs1spin6;
Spinner cs1spin7;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.laycsesem1);
ArrayAdapter<CharSequence> grade = ArrayAdapter.createFromResource(this,
R.array.grade_list, android.R.layout.simple_spinner_item);
grade.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cs1spin1.setAdapter(sem_adapter);
cs1spin1.setOnItemSelectedListener(this);
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// Completely blank after this.
}
I need to apply the same for all the spinners. I have 7 in total in my XML file.
A method which I thought of was, Since my ITEMS on the Spinners can be converted to String, I could have used a switch (String) but Android is compiled under Java 1.5,1.6 ..and switch(String) is a featured in Java 1.7. So cannot use this.
I suggest you to create a custom adapter that holds objects like
public class Grade{
String mLabel;
Float mValue;
.......
}
Look at that answer and this example.
So define that list of objects as a member of your Acticity/ Fragment.
After that in onItemSelected take you object by a given position.
You can use a HashMap, which you can use 'A+' for example as a key, and 10 as a value. So, when the user clicks on 'A+', you can find in HashMap what is the key that has the value A+ and consequently you can find the value 10.
Here is an example how can you do it using Hashap:
Map<String, Double> grades = new HashMap<String, Double>();
grades.put("A+", 10.0);
grades.put("B+", 8.5);
//You can use grades.get(your_spinner.getSelectedItem())
System.out.println(grades.get("A+"));

how to read items from string-array on android

I got a problem with reading items from string-array one by one. For example, i got string-array with 10 items:
<string-array name="arr">
<item>First</item>
<item>Second</item>
<item>...</item>
<item>Tenth</item>
</string-array>
So i know how to display items randomly, im using this code
Resources res = getResources();
myString = res.getStringArray(R.array.arr);
int length=myString.length;
int index=rgenerator.nextInt(length);
String q = myString[index];
tv = (TextView) findViewById(R.id.text);
tv.setText(q);
And in TextView on every button click it displays random item from array.
Problem is, how to make display item from string-array not randomly. Like, it starts from displaying First, then on click it displays Second, and so on untill end of array.
Please help!
You can't initialize your testArray field this way, because the application resources still aren't ready.
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);
}
}
Declare a variable
int currentIndex=0;
outside this onClick method.
In the
onClick(View v)
{
//Verify if only that btn is clicked
{
tv.setText(myString[(currentIndex++)%(myString.length)]);
}
}
Hope it works.
try
int i=0;
String q = myString[i];
i++;
strings.xml
<string-array name="month">
<item>Jan</item>
<item>Feb</item>
<item>Mar</item>
<item>Apr</item>
<item>May</item>
<item>Jun</item>
<item>Jul</item>
<item>Aug</item>
<item>Sep</item>
<item>Oct</item>
<item>Nov</item>
<item>Dec</item>
</string-array>
java
for (int i = 0; i < getResources().getStringArray(R.array.month).length; i++) {
Log.e("Array",""+getResources().getStringArray(R.array.month)[i]);
}

Setting TextView with string from string array chosen in a ListView in Android

Alright, a quick summary. The app opens with a listView (populated by a string array), when you tap one of the items in the list it takes you to another listView (populated by a string array) with items associated with the first item you tapped. In the second listView, i'd like to tap on an item and have it display a textView with associated items from another string array. I have the first two listViews working so far, but can't get the textView to work. I've banged my head over this for two days now and am getting very frustrated. Could you please help?!
Here is my strings xml file:
<string-array name="topics">
<item>Idioms</item>
<item>Travel</item>
<item>Small Talk</item>
<item>Tips</item>
<item>App Data</item>
</string-array>
<string-array name="idioms">
<item>Cash Chow</item>
<item>No Spring chicken</item>
</string-array>
<string-array name="travel">
<item>Asking for Change</item>
<item>Bus and Train Schedule</item>
</string-array>
<string-array name="idioms_description">
<item>A cash cow is a blah blah blah</item>
<item>No spring chicken means blah blah blah</item>
</string-array>
<string-array name="travel_description">
<item>This is a test for Asking for change</item>
<item>This is a test for Bus and train schedules</item>
</string-array>
And here is my getIntent and place where I should setText. I left it blank because everything I have tried until now has failed miserably, I just don't know how to get the proper string from the array that was selected.
public class DetailLanguagePoints extends Activity{
private int position;
private TextView mLanguagePoint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_view);
mLanguagePoint = (TextView) findViewById(R.detail.languagepoints);
Bundle extras = getIntent().getExtras();
//int[] arrayIds = new int[]{R.array.idioms, R.array.travel};
position = extras.getInt("listposition");
int[] stringarrayIds = new int[]{R.array.idioms_description, R.array.travel_description};
String[] subTopics = getResources().getStringArray(stringarrayIds[position]);
String description = subTopics[position];
final String TAG = "MyActivity";
Log.d(TAG,description);
mLanguagePoint.setText(description);
}
}
I found what the problem was with the null exception error, I didn't call findViewById() after setcontentView(). I did that and it solved the problem, it is now working!! Thank you to all those who provided suggestions!!
use this code mPosition = i.getIntExtra("listposition");
instead of this mPosition = i.getIntExtra("listposition", 0);
So you only want to set subTopics into a ListView?
ListView listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, subTopics);
listView.setAdapter(adapter);
Otherwise please post how you are failing with any logcat errors.
What do you want to display in the TextView? The two sub-items separated by a new line? If so then just change mLanguagePoint.setText() to mLanguagePoint.setText(subTopics[0] + "\n" + subTopics[1])
first initialize mLanguagePoint. try something like
then on second listview add onItemClickListener()
public void onItemClick(AdapterView<?> arg, View view, int position,long id) {
mLanguagePoint.setText(subTopics[position]);
}

Dynamically add items in list view

I want to make a dynamic list view which gets the user credentials when I login for the first time and displays it in a list the next time I start the app. I know how to send the username from one intent to another. i haven't focused on the SQLite part yet, will do that later. I'm facing problems in creating the dynamic list view.
Found one very useful thread - Dynamically add elements to a listView Android
he used a button on the screen and called the method onClick to populate the list. Can i do it without the button? I want it to automatically happen once i am able to login.
how can i use the statements in my code?
listItems.add(value);
adapter.notifyDataSetChanged();
here value is the username i am getting from some other intent.
please help. thanks!
For this Just use the example given below:
For Instance you are Adding Some Strings into your List
So Create a ListArray like this
ArrayList<String> listItems = new ArrayList<String>();
now whenever you want to add certain string into list just do this thing
EditText editText = (EditText) findViewById(R.id.edit);
listItems.add("my string"); OR
listItems.add(editText.getText.toString()); //incase if you are getting string value from editText and adding it into the list
Use this Xml inside your linear layout in main.xml
<EditText android:id="#+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Now when you have added one item dynamically then call this
adapter.notifyDataSetChanged();
The above will update your list and display the upadted list.
For more info about this see the following links:
http://www.androidpeople.com/android-custom-listview-tutorial-part-1
http://www.androidpeople.com/android-custom-listview-tutorial-part-2
http://www.androidpeople.com/android-custom-dynamic-listview-%E2%80%93part3
In these tutorials you can replace String[] with ArrayList as given at the top of the answer ook and when you want to add any item just simply use the second code snippet.
Thanks
sHaH
The best way to do this will be to use ArrayAdapter. When modifying the adapter it automatically refresh itself so you don't have to call notifyDataSetChanged.
You can try out this code to add elements dynamically to list view.
You can do it with out button click also.
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
//step2 : create all the variables.
EditText et;
Button b;
ListView lv;
ArrayList<string> al;
ArrayAdapter<string> aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//step3 : intitalize all the variables.
et = (EditText) findViewById(R.id.editText1);
b = (Button) findViewById(R.id.button1);
lv = (ListView) findViewById(R.id.listView1);
al = new ArrayList<string>();//initialize array list
aa = new ArrayAdapter<string>(this,
android.R.layout.simple_list_item_1,
al);//step4 : establish communication bw arraylist and adapter
//step5 : establish communication bw adapter and dest (listview)
lv.setAdapter(aa);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent,
View v, int arg2,
long arg3) {
String item = al.get(arg2);
Toast.makeText(getApplicationContext(), item, 0).show();
}
});
//step6 : button click logic
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//step i: take text from et and add to arraylist
String item = et.getText().toString();
al.add(0, item);
//step ii: notify to adapter
aa.notifyDataSetChanged();
//step iii: clr edit text
et.setText("");
}
});
}
}
For complete code check this list view example

Categories

Resources