I have a spinner that is dynamically loaded with data as following
final String[] sku = CrownApplication.mDb.getAllSKUs(Qsearch);
if((sku.length>=1)){
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(CrownTakeOrder.this,android.R.layout.simple_spinner_item, sku);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpner.setAdapter(dataAdapter);
}
This works fine,now I have a button that on clicking gets the value and sets other fields blank e.g Edittext as below. The only problen is I am not able to clear the spinner so once everything else is cleared the spinner still remains with the old Values
if (!mError) {
mSKU = mSpner.getSelectedItem().toString();
Qsearch =mQuery.getText().toString();
quantity =mQuantity.getText().toString();
String[] parts = mSKU.split(" - ");
str1 = parts[0];
str2 = parts[1];
addBody(Qsearch,mSKU,quantity);
mQuery.setText("");
mTxtview.setText("");
mQuantity.setText("");
mSKU = "empty";
//mSpner.setAdapter(null);
}
I have tried to use
mSpner.setAdapter(null);
But my app crashes....How to empty spinner? I am coding on
android:minSdkVersion="11"
android:targetSdkVersion="15"
try this
mSpner.setAdapter(new ArrayAdapter<String>(CrownTakeOrder.this, android.R.layout.simple_spinner_item, new String[]));
Related
I have a dropdown which takes its values from a database, I then want to add a default value to the existing drop down values. In this case the default value would be the selected value.
StringBuilder strbuilder = new StringBuilder();
ArrayList<String> arr_list = new ArrayList<String>();
List<String> m = new ArrayList<String>();
//This get the data values from database
m = db.getData();
int ms = m.size();
String str = strbuilder.toString();
String[] str1 = str.split(",");
try {
if (ms > 1) {
//This is my default value
m.add("Default Value");
for (int i = 0; i < ms; i++) {
m.get(0);
}
} else {
m.get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, m);
dropdown.setAdapter(adapter);
The codes above is able to add the values from the database to the dropdown and the Default Value is added but it doesn't appear to be the selected value.
For instance if the values from the database are "Apple, Mango,Pineapple" and the default value is "ALL FRUITS".
EXPECTED DROPDOWN
ALL FRUITS
Apple
Mango
Pineapple
Please how can I do make the default value the selected value? Thanks in advance.
I think you need below code.
List<String> categories = new ArrayList<String>();
categories = db.getData();
categories.add(0,"your_default_value");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setSelection(0);
Remember when you want to add any value to the very first of Arraylist you just do
arraylist.add(0,"value");
This will add the value to the very first index of arraylist and push all other element down.
In case you need any other element to be selected not first one
Spinner spinner = (Spinner) findViewById(R.id.spinner);
List<String> categories = new ArrayList<String>();
categories.add("Automobile");
categories.add("Business Services");
categories.add("Computers");
categories.add("Education");
categories.add("Personal");
categories.add("Travel");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
int i=categories.indexOf("Education");
spinner.setSelection(i);
If the default value is always going to be at the 0 index, just get a reference to your dropdown/spinner, then set:
spinner.setSelection(0);
And here is a previously answered question detailing how to set it by value, if you'd rather do that.
https://stackoverflow.com/a/4228121/3299157
Been scouring this site for any answers, no real easy solution I've found for this. I am creating an Android application that uses an sqlite database to look up a hex value by the color name typed in. I am dynamically creating a TextView, setting its text and text color, then adding it to the ArrayList, then the ArrayList is being added to the ListView. The text shows up in the ListView, but its color property is not being set. I'd really like to find a way to get the text color set for each listview item. Here is my code thus far:
Class Variables:
private ListView lsvHexList;
private ArrayList<String> hexList;
private ArrayAdapter adp;
In onCreate():
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.color2hex);
lsvHexList = (ListView) findViewById(R.id.lsvHexList);
hexList = new ArrayList<String>();
In my Button Handler:
public void btnGetHexValueHandler(View view) {
// Open a connection to the database
db.openDatabase();
// Setup a string for the color name
String colorNameText = editTextColorName.getText().toString();
// Get all records
Cursor c = db.getAllColors();
c.moveToFirst(); // move to the first position of the results
// Cursor 'c' now contains all the hex values
while(c.isAfterLast() == false) {
// Check database if color name matches any records
if(c.getString(1).contains(colorNameText)) {
// Convert hex value to string
String hexValue = c.getString(0);
String colorName = c.getString(1);
// Create a new textview for the hex value
TextView tv = new TextView(this);
tv.setId((int) System.currentTimeMillis());
tv.setText(hexValue + " - " + colorName);
tv.setTextColor(Color.parseColor(hexValue));
hexList.add((String) tv.getText());
} // end if
// Move to the next result
c.moveToNext();
} // End while
adp = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hexList);
lsvHexList.setAdapter(adp);
db.close(); // close the connection
}
You are not adding the created TextView to the list at all, you just add the String to the list, thus it doesn't matter what method you called on the TextView:
if(c.getString(1).contains(colorNameText)) {
// ...
TextView tv = new TextView(this);
tv.setId((int) System.currentTimeMillis());
tv.setText(hexValue + " - " + colorName);
tv.setTextColor(Color.parseColor(hexValue));
hexList.add((String) tv.getText()); // apend only the text to the list
// !!!!!!!!!!!!!! lost the TextView !!!!!!!!!!!!!!!!
}
What you need to do is to store the colors in another array, and when creating the actual list view, set the color of each TextView according to the appropriate value in the list.
To do that, you will need to extend ArrayAdapter and add the logic of the TextView color inside.
I have within a TabActivity a Spinner that will be generated dynamically. Just to test, I did so manually:
Spinner sp_departure = (Spinner) findViewById(R.id.spinner_departure);
// This array will be generated through a database
String[] array_spinner = new String[2];
array_spinner[0] = "Departure 1";
array_spinner[1] = "Departure 2";
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array_spinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp_departure.setAdapter(adapter);
When I run the app looks ok since option selected is "Departure 1" but when I click to open the options I get some errors and the application is closed.
Any idea what could be wrong?
Thanks in advance.
- Update
This is what was generated by LogCat: http://pastebin.com/1QPKZdKB
Yes you might have set setContetView(R.layout.yourxml)...,
Change it to :
View viewToLoad = LayoutInflater.from(this.getParent()).inflate(R.layout.yourxm, null);
this.setContentView(viewToLoad);
and use
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getParent(), android.R.layout.simple_spinner_item, array_spinner);
Try, it may helps you
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
This question already has answers here:
How to make an Android Spinner with initial text "Select One"?
(36 answers)
Closed 9 years ago.
The first year from the data array is shown instead of the text from prompt in my spinner. I tried adding the prompt in XML, but I also tried from code. Furthermore, it gives me a "resource not found error", when adding the spinnerSelector attribute.
XML
<Spinner
android:id="#+id/spinnerYear"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:drawSelectorOnTop="true"
android:padding="5dip"
android:prompt="#string/spinner_header"
android:background="#drawable/selector_yearspinnerback"
android:layout_below="#+id/linearLayout_gender_btns"
android:layout_centerHorizontal="true"></Spinner>
-- android:spinnerSelector="#drawable/category_arrow"
Code
ArrayList<String> yearList = new ArrayList<String>();
int now = new Date().getYear() + 1900;
for (int i = now; i > now - 110; i--) {
yearList.add(i + "");
}
Spinner spinner = (Spinner) findViewById(R.id.spinnerYear);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, yearList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Perhaps you are seeing the spinner drop down items as list without any prompt text. There are two modes in which spinner shows the items, dropdown and dialog.
Add this attribute to your spinner as an XML atrtribute:
android:spinnerMode="dialog"
And you will now get items in a popup dialog select list instead of drop down list.
You have to set adapter.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item); after
spinner.setAdapter(adapter);
So the fixed code would be:
ArrayList<String> yearList = new ArrayList<String>();
int now = new Date().getYear() + 1900;
for (int i = now; i > now - 110; i--) {
yearList.add(i + "");
}
Spinner spinner = (Spinner) findViewById(R.id.spinnerYear);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, yearList);
spinner.setAdapter(adapter);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
(I hope it works for you like it works for me :D!)
For me, both android:prompt XML attibute as well as Spinner.setPrompt work, and list selector displays correct title.
Try to find bug in your code, or make call to Spinner.getPrompt at some point and print this to log, to find our from where you get invalid title.