How to save selection id's from listview - android

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()

Related

spinner key and value

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) {
}
});
}
}

How to set country code in textview to select country name in spinner?

This is main XML:
<Spinner
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_height="40sp"
android:layout_marginTop="37dp"
android:layout_below="#+id/textView2"
android:layout_toLeftOf="#+id/button"
android:layout_toStartOf="#+id/button"
android:layout_marginRight="29dp"
android:layout_marginEnd="29dp" />
<TextView
android:id="#+id/countrycode"
android:layout_width="wrap_content"
android:text="+"
android:textSize="30sp"
android:layout_height="40sp"
android:ems="10"
android:layout_alignTop="#+id/spinner"
android:layout_toLeftOf="#+id/editText2"
android:layout_toStartOf="#+id/editText2" />
This is my Java code:
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.List;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
TextView textview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textview = (TextView) findViewById(R.id.countrycode);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
String[] countryname = {"India", "America", "Japan", "Austrailia", "Canada" };
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countryname);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// // Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
This is my code. How can I set country code in TextView to select country name in Spinner? I want to use this code because its easy to understand for me and it's working but I can't do what I want.
I want that if I select India in Spinner then I get India ISD code (+91) is TextView.
Set a TextWatcher for your TextView:
textview.addTextChangeListener(new TextWatcher()); and implement onTextChange() method to get the typed country code from user, then put in a swich/case to determine which country name should me selected.
Use Hashtable.
class MainActivity {
....
Hashtable countryCodes<String, String>;
TextView textViewCountryCode;
....
onCreate(....){
....
textViewCountryCode = (TextView) findViewById(R.id.countrycode);
countryCodes = new Hashtable<>();
countryCodes.put("India", "+91");
....
}
....
onItemSelected(....){
....
String countryCode = countryCodes.get(item);
textViewCountryCode.setText(countryCode);
....
}
}
What I understood is you want the answer in the code provided by you . So what you can do is take one more array of Country code and On Spinner onSelected method set the selected position to the text view but make sure to keep the Country name and country code index same .Or i would recommend do it using HashMap for the same.
// add this below before oncreate
TextView textview;
String[] countrycode = {"+91", "+1", "+81", "+61", "+1" };
and in onItemSelected() method do this
textview.setText(countrycode[position]);

How to setup multi-line listview using separate string-arrays (Android)

I am working on an application in Android that works with 2 screens. The firsts creen is simple, it has a TextView initialzed to "Not Set" and a Button. When the user clicks on the button, he/she is taken to the 2nd screen which is one big ListView. The ListView is a list of all highest grossing movies of all time. It would be simple if it were to include just the title, but I need to create the listview such that it has multiple lines. The structure being, the title is oriented left, the gross earnings aligned right and the date released is located on a second row.
The important tidbit is that I need to use string arrays declared at the strings.xml. I have already declared all of them, however my problem is that I am stuck on how to make the Java portion. Here is what I have come up so far.
package com.android.rondrich;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Lab5_082588part2 extends ListActivity {
public static final String KEY = "KEY";
public static final String RETURN = "RETURN";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] titleList = getResources().getStringArray(R.array.title_array);
String[] grossList = getResources().getStringArray(R.array.gross_array);
setListAdapter(new ArrayAdapter<String>(this,
R.layout.lab5_082588part2, grossList)); //not sure if correct to have 2 setListAdapters
setListAdapter(new ArrayAdapter<String>(this,
R.layout.lab5_082588part2, titleList));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = getIntent();
String title = ((TextView) view).getText().toString();
intent.putExtra(Lab5_082588part2.RETURN, title);
setResult(RESULT_OK, intent);
finish();
}
});
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
}
Some of the snippets I have researched are using this kind of approach (sample code)
private ArrayList<SearchResults> GetSearchResults(){
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr = new SearchResults();
sr.setName("Justin Schultz");
sr.setCityState("San Francisco, CA");
sr.setPhone("415-555-1234");
results.add(sr);
However this method will prove very tedious for long lists. The question is that:
How do I incorporate using string arrays declared in strings.xml to have multi-line listview without resorting to hardcoding it like above?
You can't set the adapter two times to show the row like you want instead you have to implement a custom adapter(there are thousands of tutorials out there to look at so I'll leave this part out).
To extract the data from the strings arrays you would(almost) use the snippet you posted:
String[] titleList = getResources().getStringArray(R.array.title_array);
String[] grossList = getResources().getStringArray(R.array.gross_array);
// ...
private ArrayList<SearchResults> GetSearchResults(){
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
// make sure the arrays have the same length
for (int i = 0; i < titleList.length; i++) {
SearchResults sr = new SearchResults();
sr.setTitle(titleList[i]);
sr.setGross(grossList[i]);
results.add(sr);
}
return results;
}
Then you would use the list returned by this method to fill your custom adapter.
A layout example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="title" />
<TextView
android:id="#+id/gross"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/title"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Gross" />
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#id/title"
android:text="Date" />
</RelativeLayout>
How to make custom ListView items you can read in this tutorial: http://www.ezzylearning.com/tutorial.aspx?tid=1763429
If you want to get String from your strings.xml use that in your ativity class:
getContext().getResources.getString(R.string.your_text);

Modifying this List Linstners (custom adapter)

Can someone please tell me how to create a custom adpater for this list, as i dont want toast to display when a user clicks the list item, but, When a user clicks on Google, he will be navigated to "www.google.com" and "www.yahoo.com" and same for msn.com,,
cant figure out at all, stuck for last 1 week, even though i know how to create a intent and call a URI but not working or right for this,
can someone just modify this please ?
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class FurtherEducationCourses extends ListActivity
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, FURTHER_EDUCATION));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
}
static final String[] FURTHER_EDUCATION = new String[] {
"GOOGLE", "YAHOO", "MSN"
};
}
xml file, dunno why u required :s
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
The trick is to get the item at that position, then depends on the position (or even the value at the position), you call the correct link.
So you need to index the value like this, put this code after your static final... statement.
HashMap<String, String> valueToLink = new HashMap<String, String>;// key is Google, Yahoo, value is www.google.com
valueToLink.put("GOOGLE", "www.google.com");
//add yahoo,.etc.
In onItemClick() function, replace the toast by this:
String link = valueToLink.get(((TextView) view).getText());
//code to open the link here

android's ListView does not listen on single clicks

I'm developing an simple application on Android, where some items are shown on a list. The user may click on one, taking him to a further activity. Basics...
But my OnItemClickListener does not get called! I've found this very similar question, but the solution (disallow the list item view to get focus) does not work for me. However, a long click gets catched - my OnItemLongClickListener gets called. Please have a look at the following code and try it yourself. This is a simplified version of my code, showing the buggy behavior. Btw: I'm using Andriod SDK 2.0 with Eclipse 3.5.1.
package de.sacherkhoudari.listtest;
import java.util.LinkedList;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
public class ListTest extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final List<ListEntry> lEntries = new LinkedList<ListEntry>();
for ( int ii = 0; ii < 10; ii++ )
lEntries.add( new ListEntry( "Entry " + ii ) );
setListAdapter( new ArrayAdapter<ListEntry>( this, R.layout.list_item, lEntries ) );
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener( new OnItemClickListener() {
public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
Toast.makeText( ListTest.this, "ItemClick at item " + lEntries.get(position).toString(), Toast.LENGTH_LONG ).show();
}
});
lv.setOnItemLongClickListener( new OnItemLongClickListener() {
public boolean onItemLongClick( AdapterView<?> parent, View view, int position, long id ) {
Toast.makeText( ListTest.this, "ItemLongClick at item " + lEntries.get(position).toString(), Toast.LENGTH_LONG ).show();
return false;
}
});
setContentView(lv);
}
}
class ListEntry {
private String name;
public ListEntry( String s ) {
name = s;
}
public String toString() {
return name;
}
}
So far the Java code... here comes the layout list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp"
android:focusable="false" >
</TextView>
Note: android:focusable="false" has no effect.
Thanks!
Sacher
When you add layouts with setContentView, views within that layouts get freshly instanciated. The ListActivity has a very simple Layout by default (read about it here), even if you don't add your own layout. So basically in your first example:
First you add a listener to the default ListView within the ListActivity
Then you throw that ListView away by using setContentView to instanciate a new layout with a new ListView
Then you never register a new listener to the new ListView from your new layout.
Whereas when you pull setContentView up in your code you only ever work with your own ListView and everything works as expected.
Move your setContentView(lv); right after retrieving the ListView
ListView lv = getListView();
setContentView(lv);
lv.setTextFilterEnabled(true);

Categories

Resources