How To Give Position Zero Of Spinner A Prompt Value?
The database is then transferring the data to a spinner which I want to leave position 0 blank so I can add a item to the spinner with no value making it look like a prompt. I hav
Solution 1:
You're getting the data from db in al
ArrayList. Then you can do the following
al.add(0, "YOUR MESSAGE");
It adds YOUR MESSAGE string at 0th
index.
Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
After this pass the list to arrayadapter
ArrayAdapter<String> aa1 = newArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_spinner_item,
al);
spn.setAdapter(aa1);
Please do check ArrayList
EDIT
Here is the code
publicvoidloadtospinner() {
ArrayList<String> al = newArrayList<String>();
Cursor c = SQLcon.readData();
c.moveToFirst();
while (!c.isAfterLast()) {
String name = c.getString(c.getColumnIndex(DBhelper.MEMBER_NAME));
String calories = c.getString(c
.getColumnIndex(DBhelper.KEY_CALORIES));
al.add(name + ", Calories: " + calories);
c.moveToNext();
}
al.add(0, "YOUR MESSAGE"); // do this after while loop and that's it. ArrayAdapter<String> aa1 = newArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_spinner_item,
al);
spn.setAdapter(aa1);
// closing databaseSQLcon.close();
}
Solution 2:
Use the following:
Spinner spinner = (Spinner) findViewById(R.id.yourSpinner);
ArrayAdapter<String> spinnerArrayAdapter = newArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinnerArray);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
Update:
Your spinnerArray should have values from database with first value as prompt
For example:
List<String> spinnerArray = newArrayList<String>();
spinnerArray.add("YOU MESSAGE");
And then you can use for loop to add values to spinnerArray as follow:
for(//loop until you need values to be added)
Add values to spinnerArray as:
spinnerArray.add(value1);
spinnerArray.add(value1);
spinnerArray.add(value1);
//so on.
and finally pass it as last argument while creating spinnerArrayAdapter as above. And this should solve your problem.
Update1:
If you don't want to get item at position 0 you can do the following:
if(spinner.getSelectedItem().equals("YOUR MESSAGE"){//may be you want to ignorecase using equalsIgnoreCase() method//display message that you haven't selected anything
}else{
//do anything you want
}
Populate dummy data:
Change your onCreate() in DBhelper class to:
@OverridepublicvoidonCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
ContentValuescv=newContentValues();
cv.put(DBhelper.MEMBER_NAME, "DUMMY NAME");
cv.put(DBhelper.KEY_CALORIES, "DUMMY CALORIES");
database.insert(DBhelper.TABLE_MEMBER, null, cv);
}
Post a Comment for "How To Give Position Zero Of Spinner A Prompt Value?"