I am developing a translate app on Android Studio. I have created my Language Key and Value using Map, I want to pass the value of key selected by the user to URL. for example if the user selects French from Spinner, "fr" should be pass to url for translate. how can I achieve this? below is my Java Activity Code. I am using the latest Android Studio.
spinner = (Spinner) findViewById(R.id.spinner);
final Map<String, String> flanguages = new HashMap<String, String>();
flanguages.put("Arabic", "ar");
flanguages.put("English", "en");
flanguages.put("French", "fr");
flanguages.put("Hausa", "ha");
flanguages.put("Igbo", "ig");
flanguages.put("Yoruba", "yo");
flanguages.put("Japanese", "ja");
final List<String> list = new ArrayList<String>(flanguages.keySet());
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
spinner.setPrompt("Select Language To Translate");
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinner.getItemAtPosition(position).toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner.getItemAtPosition(position).toString(); //returns country Full-name
This line gives your the selected item i.e the country name but not its abbreviation. To get the abbreviation to use the HashMap(use the Key to get the Value).Ex: Here key is "France" and its value is "fr"
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String key = spinner.getItemAtPosition(position).toString(); //ex: this gives France
// String key = list.get(position); // or use can use this,//ex: this also gives France
String countryCode = flanguages.get(key); //ex: this gives "fr"
//api integration
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});