As i am newbie in android i want to show my saved spinner value at the time of view of saved form
how can i show database saved value at the time of view for spinner
here is my code
Java activity file
Spinner spnAECust;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ae_view_edit_sales);
spnAECust = (Spinner) findViewById(R.id.spnAECust);
/* Get Customer List and Add Select Default */
cust = con.getAllCustomers();// from database getting list
List<Customer> custList = new ArrayList<Customer>();
Customer c = new Customer();
c.setId(Constants.Common.ZERO);
c.setNm("Select Customer");
custList.add(c);
custList.addAll(cust);
// Create and fill an ArrayAdapter with a bunch of "Customer" objects
ArrayAdapter<Customer> custArrayAdapter = new ArrayAdapter<Customer>(this, android.R.layout.simple_spinner_item,
custList.toArray(new Customer[custList.size()]));
// Tell the spinner about our adapter
spnAECust.setAdapter(custArrayAdapter);
sa = con.getAirSalesActivityDetails(Integer.parseInt(saId));// get details from Sqlite
Customer cust = new Customer();
cust.setId(sa.getCustomerId());
spnAECust.setSelection(custArrayAdapter.getPosition(cust));// to set value saved in db
}
at tried setSelection but it maches index value rather than id value so i get abstract value to b selected please show me correct way to implement ...Thnks in advance
Here i got answer by my own
/* Get Customer List and Add Select Default */
cust = con.getAllCustomers();
List<Customer> custList = new ArrayList<Customer>();
Customer cst = new Customer();
cst.setId(Constants.Common.ZERO);
cst.setNm(Constants.Common.CUSTOMER_HINT);
custList.add(cst);
custList.addAll(cust);
/* Get Commodity List and Add Select Default */
comm = con.getAllCommodities();
List<Commodity> commList = new ArrayList<Commodity>();
Commodity cm = new Commodity();
cm.setId(Constants.Common.ZERO);
cm.setNm(Constants.Common.COMMODITY_HINT);
commList.add(cm);
commList.addAll(comm);
// Create and fill an ArrayAdapter with a bunch of "Customer" objects
ArrayAdapter<Customer> custArrayAdapter = new ArrayAdapter<Customer>(this, android.R.layout.simple_spinner_item,
custList.toArray(new Customer[custList.size()]));
int custIndex = 0;
// to set selected item
for (int r = 0; r < custArrayAdapter.getCount(); r++) {
if (sa.getCustomerId() == custArrayAdapter.getItem(r).getId()) {
custIndex = r;
break;
}
}
// Tell the spinner about our adapter
spnAECust.setAdapter(custArrayAdapter);
spnAECust.setSelection(custIndex);
// Create and fill an ArrayAdapter with a bunch of "Commodities" objects
ArrayAdapter<Commodity> commArrayAdapter = new ArrayAdapter<Commodity>(this, android.R.layout.simple_spinner_item,
commList.toArray(new Commodity[commList.size()]));
int commIndex = 0;
// to set selected item
for (int r = 0; r < commArrayAdapter.getCount(); r++) {
if (sa.getCommodityId() == commArrayAdapter.getItem(r).getId()) {
commIndex = r;
break;
}
}
// Tell the spinner about our adapter
spnAEComodity.setAdapter(commArrayAdapter);
spnAEComodity.setSelection(commIndex);
used for loop to get index for saved value
int commIndex = 0;
// to set selected item
for (int r = 0; r < commArrayAdapter.getCount(); r++) {
if (sa.getCommodityId() == commArrayAdapter.getItem(r).getId()) {
commIndex = r;
break;
}
}
and add index to
spnAEComodity.setSelection(commIndex);
Related
How to get value to dynamically add multiple spinner where spinner id is same.i used 'String spin = parent.getSelectedItem().toString();' but i get all time last spinner value.Plz help me?
you can create array list of spinner
ArrayList<Spinner> listSpinner = new ArrayList<>();
listSpinner.add(spinner1);
listSpinner.add(spinner2);
listSpinner.add(spinner3);
for(int i=0;i<listSpinner.size();i++){
String p1 = listSpinner.get(i).getSelectedItem();
}
get different value for all spinner out side for loop and store it in arraylist.
ArrayList<Spinner> listSpinner = new ArrayList<>();
ArrayList<ArrayList<String>> status_list = new ArrayList<>();
status_data.add("" + snapshot.getValue());// getting data
status_list.add(status_data);
for (int i = 0; i < 10; i++) {
View v = LayoutInflater.from(AssetCodingDetails.this).inflate(R.layout.custom_asset_coding_label, null);
Spinner spinner_status = (Spinner) v.findViewById(R.id.spinner_status);
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), R.layout.spinner_item, status_list.get(i));
spinner_status.setAdapter(adapter);
listSpinner.add(spinner_status);
}
for(int i=0;i<listSpinner.size();i++){
String p1 = listSpinner.get(i).getSelectedItem().toString();
}
I am creating an android app in which I want to add values in spinner i.e countries. I added them successfully, but I want to show my desire country at the top of the spinner list i.e I want to show Australia at the 0 index of the spinner. So how I can achieve this? Anyone please help me.
Here is my code:
MySpinnerAdapter adapter = new MySpinnerAdapter(SignUp.this, android.R.layout.simple_spinner_item, countryname);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_country.setAdapter(adapter);
spinner_country.setSelection(countryname.size() - 1);
spinner_country.setSelection(12);
Collections.sort(countryname);
Now I am doing this and it shows ArrayIndexOutOfBoundsException
String[] str = new String[countryname.size()-1];
str = countryname.toArray(str);
int indexTarget = 13;
String valueAtIndex = str[indexTarget];
for(int i = indexTarget; i > 0; i--){
str[i] = str[i-1];
}
str[0] = valueAtIndex;
for (int i = 0; i < str.length; i++)
{
System.out.println(str[i]);
}
List<String> stringList = new ArrayList<String>(Arrays.asList(str));
MySpinnerAdapter adapter = new MySpinnerAdapter(SignUp.this, android.R.layout.simple_spinner_item, stringList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_country.setAdapter(adapter);
spinner_country.setSelection(countryname.size() - 1);
Collections.sort(countryname);
If you want Australia to be at the first position in spinner then add it to zeroth index of your countryname.
You can start adding names to your countryname with Australia so that it will be at zeroth index and appear at first position in spinner.
spinner.setSelection(12) will select the 13th value from the array you are supplying to your adapter. It will not be at the first position.
EDIT
This is just an example, you need to modify accordingly. Here the original array is B, M, T, A, C, I want A to be first, so I need index of A. For your question you need the index of Australia
String[] str = {"B", "M", "T", "A", "C"};;
int indexTarget = 3;
String valueAtIndex = str[indexTarget];
for(int i = indexTarget; i > 0; i--){
str[i] = str[i-1];
}
str[0] = valueAtIndex;
for (int i = 0; i < str.length; i++)
System.out.println(str[i]);
Output
A
B
M
T
C
Now A is at first position.
I have:
a String array with an unknown length that's populated with unknown items (let's say fish, bird, cat)
an ArrayAdapter and a Spinner that displays the items
a variable that contains one unknown item from the string array (let's say cat)
I want to set the Spinner to the value from the variable (cat). What's the most elegant solution? I thought about running the string through a loop and comparing the items with the variable (until I hit cat in this example), then use that iteration's # to set the selection of the Spinner, but that seems very convoluted.
Or should I just ditch the Spinner? I looked around and found a solution that uses a button and dialog field: https://stackoverflow.com/a/5790662/1928813
//EDIT: My current code. I want to use "cow" without having to go through the loop, if possible!
final Spinner bSpinner = (Spinner) findViewById(R.id.spinner1);
String[] animals = new String[] { "cat", "bird", "cow", "dog" };
String animal = "cow";
int spinnerpos;
final ArrayAdapter<String> animaladapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, animals);
animaladapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bSpinner.setAdapter(animaladapter);
for (Integer j = 0; j < animals.length; j++) {
if (animals[j].equals(animal)) {
spinnerpos = j;
bSpinner.setSelection(spinnerpos);
} else {
};
}
(Temporarily) convert your String array to a List so you can use indexOf.
int position = Arrays.asList(array).indexOf(randomVariable);
spinner.setSelection(position);
EDIT:
I understand your problem now. If your String array contains all unique values, you can put them in a HashMap for O(1) retrieval:
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < animals.length; i++) {
map.put(animals[i], i);
}
String randomAnimal = "cow";
Integer position = map.get(randomAnimal);
if (position != null) bSpinner.setSelection(position);
i have a array list for using it in spinner ,i have first value i spinner as title and i want to sort array list from second item in the spinner but i dont know how to do this i am using below trick but it sort whole array list including first item which is title so how to statr sorting from second item...
my code is below...
// this is my title ie. "provincia"
String select2= "Provincia";
if(!estado1.contains(select2)){
estado1.add(select2);
}
for (int i = 0; i < sitesList1.getEstado().size(); i++)
{
if(!estado1.contains(sitesList1.getEstado().get(i)))
{
estado1.add(sitesList1.getEstado().get(i));
Collections.sort(estado1);
}
use below code for show it in spinner...
final ArrayList<String> estado1 = MainMenu.barrio1;
final Spinner estado11 = (Spinner) findViewById(R.id.Spinner04);
ArrayAdapter<String> adapterbarrio = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, estado1)
estado11.setAdapter(adapterbarrio);
Why not remove the title / only add the title after the list has been sorted?
How about this
List<String> list = new ArrayList<String>();
// Fill list
String title = list.get(0);
list.remove(0);
Collections.sort(list);
list.add(0, title);
One way would be to split the arraylist like
estado1.subList(1,estado1.size()-1);
This would return a sublist excluding your title.
Use bubble sort! and start at index = 1!
final ArrayList<String> estado1;
for(int i=1; i<estado1.size() ; i++) {
for(int c=i; c<estado.size() ; c++) {
if(estado1.get(i).compareTo(estado1.get(c)))
{
String temp = estado1.get(i);
estado1.remove(i);
estado1.add(i, estado1.get(c));
estado1.remove(c);
estado1.add(c, temp);
}
}
}
PS: very bad performance
I have created a simple Spinner binding it to a SimpleCursorAdapter. I'm populating the SimpleCursorAdapter with a list of towns from a content provider.
When I go to save the users selection I'm planning on saving the row id that is being populated into my SimpleCursorAdapter.
I'm using the following code to get the ID.
townSpinner.getSelectedItemId();
What I can not figure out is how best to set the selection when I pull back up the saved item.
The following code works but it only sets selection by position number.
townSpinner.setSelection(2);
Should I just create a loop to determine the correct position value based on Id?
long cityId = Long.parseLong(cursor.getString(CityQuery.CITY_ID));
for (int i = 0; i < citySpinner.getCount(); i++) {
long itemIdAtPosition2 = citySpinner.getItemIdAtPosition(i);
if (itemIdAtPosition2 == cityId) {
citySpinner.setSelection(i);
break;
}
}
I think you've answered your own question there!
Just write your own setSelectionByItemId method using the code you posted
Example:
DB:
public Cursor getData() {
SQLiteDatabase db = getReadableDatabase();
String sql = "select ID _id, Name from MyTable order by Name ";
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
return c;
}
Activity:
Cursor myCursor = db.getData();
SimpleCursorAdapter adapter1 = new SimpleCursorAdapter(
this,
android.R.layout.simple_spinner_item,
myCursor,
new String[] { "Name" }, new int[] { android.R.id.text1 }, 0);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter1);
for(int i = 0; i < adapter1.getCount(); i++)
{
if (adapter1.getItemId(i) == myID )
{
mySpinner.setSelection(i, false); //(false is optional)
break;
}
}
Android Spinner set Selected Item by Value
The spinner provides a way to set the selected valued based on the position using the setSelection(int position) method. Now to get the position based on a value you have to loop thru the spinner and get the position. Here is an example
mySpinner.setSelection(getIndex(mySpinner, myValue));
private int getIndex(Spinner spinner, String myString){
int index = 0;
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).equals(myString)){
index = i;
}
}
return index;
}
If you are using an ArrayList for your Spinner Adapter then you can use that to loop thru and get the index. Another way is is to loop thru the adapter entries
Spinner s = (Spinner) findViewById(R.id.spinner_id);
for(i=0; i < adapter.getCount(); i++) {
if(myString.trim().equals(adapter.getItem(i).toString())){
s.setSelection(i);
break;
}
}