load from spinner sqlite with text and value - android

i have a spinner load data to sqlite
i have field id and field name in database.
private void loadSpinnerDataHama() {
// database handler
DatabaseSpinner db = new DatabaseSpinner(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spin2.setAdapter(dataAdapter);
}
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
and the result is
USA -> value is "USA"
France -> value is "France"
when i change the code labels.add(cursor.getString(1)); to labels.add(cursor.getString(0));
and the result is
1 -> value is "1"
2 -> value is "2"
i try with int position2 = spin2.getSelectedItemPosition()+1; but the value is id/position of spinner , not the id of database.
how to display field name on spinner. but the value is id of name
Example: The spinner display:
USA -> value is "1"
France -> value is "2"
BR
Alex

It is really simple, what you can do is to implement/ represent what you need by a class, in the following manner :
Create the following class : SpinnerObject
public class SpinnerObject {
private int databaseId;
private String databaseValue;
public SpinnerObject ( int databaseId , String databaseValue ) {
this.databaseId = databaseId;
this.databaseValue = databaseValue;
}
public int getId () {
return databaseId;
}
public String getValue () {
return databaseValue;
}
#Override
public String toString () {
return databaseValue;
}
}
Using this class, you can still use the Android implementation of the ArrayAdapter (no need to implement your own, since the toString method provides the string value that you want to display, and you still store the database id that you also need).
Now you will have to create your list as follows :
public List < SpinnerObject> getAllLabels(){
List < SpinnerObject > labels = new ArrayList < SpinnerObject > ();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if ( cursor.moveToFirst () ) {
do {
labels.add ( new SpinnerObject ( cursor.getString(0) , cursor.getString(1) ) );
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning labels
return labels;
}
Now that you have the list of objects with the values and ids, you load the spinner this way :
private void loadSpinnerDataHama() {
// database handler
DatabaseSpinner db = new DatabaseSpinner(getApplicationContext());
// Spinner Drop down elements
List <SpinnerObject> lables = db.getAllLabels();
// Creating adapter for spinner
ArrayAdapter<SpinnerObject> dataAdapter = new ArrayAdapter<SpinnerObject>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spin2.setAdapter(dataAdapter);
}
And the spinner will display the values, while having their ids (from the database) too.
In order to retrieve the id of the currently selected item, you do this :
int databaseId = Integer.parseInt ( ( (SpinnerObject) spin2.getSelectedItem () ).getId () );
Please try it and let me know what happens.

Related

get id of selected spinner data based from database android

hi i have this spinner dropdown that displays data from my database. In my database, i have this table named area and it has this fields, aid its primary key and location which is a varchar. so far i am successful in displaying the data im my spinner. in my DBHelper this is the code that gets the data from DB
public Set<String> getAllData()
{
Set<String> set = new HashSet<String>();
String selectQuery = "SELECT * FROM " + TABLE_AREA;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
set.add(cursor.getString(1));
} while (cursor.moveToNext());
}
db.close();
return set;
}
then in my addLocation.java here is how i use it to display the data on my spinner
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.addplace);
Spinner spn = (Spinner)findViewById(R.id.areas);
Set<String> aset = db.getAllData();
List<String> aData = new ArrayList<>(aset);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,
aData);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(spinnerAdapter);
spn.setOnItemSelectedListener(new SpinnerInfo());
}
private class SpinnerInfo implements AdapterView.OnItemSelectedListener {
private boolean isFirst = true;
String selected;
#Override
public void onItemSelected(AdapterView<?> spinner, View selectedView, int selectedIndex, long id)
{
if (isFirst)
{
isFirst = false;
}
else
{
String selection = spinner.getItemAtPosition(selectedIndex).toString();
selected = selection;
}
Toast tempMessage =
Toast.makeText(addLocation.this,
selected,
Toast.LENGTH_SHORT);
tempMessage.show();
}
#Override
public void onNothingSelected(AdapterView<?> spinner) {
// Won’t be invoked unless you programmatically remove entries
}
}
the thing is i needed to get the id of the selected location not the index in the spinner but it's database id. any idea on how i can do this? thanks so much in advance!
i needed to get the id of the selected location not the index in the
spinner but it's database id. any idea on how i can do this?
Do it as using HashMap:
1. Use HashMap instead of Set with location as a key and location id as value. change getAllData() :
public Map<String, Integer> getAllData()
{
Map<String, Integer> hashMap = new HashMap<String, Integer>();
...
if (cursor.moveToFirst()) {
do {
hashMap.put(cursor.getString(1),cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
return hashMap;
}
2. Pass all keys to Spinner :
Map<String, Integer> hashMap = db.getAllData();
List<String> allLocations = new ArrayList<String>(hashMap.keySet());
3. Now In onItemSelected use selected String to get id of Selected item:
int location_id=hashMap.get(selected);

How to bind spinner in android using sqlite?

I have a table containing
------------------------
id |Name
------------------------
16001 |ABC
16002 |QWE
16003 |RTY
16004 |JHG
and bind it to a spinner; spinner item with name, and spinneritemposition with id.
I try this so far:
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_ite‌​m);
List<String> lables = dataSource.getAllmothers();
public List<String> getAllmothers()
{
List<String> labels = new ArrayList<String>();
database = dbHelper.getReadableDatabase(); // Select All Query
String selectQuery = "SELECT id,name FROM "+dbHelper.TABLE_REGISTRATION;
Cursor cursor = database.rawQuery(selectQuery, null); // looping through all rows and adding to list
if (cursor.moveToFirst()) {
do
{
labels.add(Integer.toString(cursor.getInt(0)));
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
} // closing connection
cursor.close();
database.close(); // returning lables
return labels;
}
create Array Adapter like this
ArrayAdapter ad=new ArrayAdapter(cureentclass,dropdownstyle,values)
values is what u r getting through the database values variable and add the bind the Array Adapter to the spinner.

Android Spinner is empty

There are no errors in my code. It works just fine except that the Spinner isn't populated from the database as expected. Rather, it is empty. Please help!!
Retrieve Records from SQLite:
// get all contacts
public List getAllNames() {
List names = new ArrayList();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
names.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
db.close();
// returning contacts
return names;
}
Load Spinner:
private void loadSpinnerData() {
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> contacts = db.getAllNames();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, contacts);
// 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);
}
I guess all it needs is a minor tweak somewhere, but I don't understand where. Thanks in advance!

SQLite to ListView(androidhive's version)

I am trying to insert data from SQLite to a listview. I have tried look for example codes but they do not work. The database part is from AndroidHive's SQL tutorial. In his post the code to get all data in DB is(i edited the data fields) :
// Getting All carts item
public List<Cart> getAllCart() {
List<Cart> cartList = new ArrayList<Cart>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Cart cart = new Cart();
cart.setID(Integer.parseInt(cursor.getString(0)));
cart.setPID(Integer.parseInt(cursor.getString(1)));
cart.setName(cursor.getString(2));
cart.setPrice(Double.parseDouble(cursor.getString(3)));
cart.setQut(Integer.parseInt(cursor.getString(4)));
// Adding cart to list
cartList.add(cart);
} while (cursor.moveToNext());
}
// return cart list
return cartList;
}
how do put this "getAllCart()" to my listview. Thanks alot!!
to get data from SQLite you can try like this:
public List<String[]> selectAll()
{
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME, new String[] { "id","name","number","skypeId","address" },
null, null, null, null, "name asc");
int x=0;
if (cursor.moveToFirst()) {
do {
String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4)};
list.add(b1);
x=x+1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
and to show it in a list view :
List<String[]> list = new ArrayList<String[]>();
List<String[]> names2 =null ;
names2 = dm.selectAll();
stg1=new String[names2.size()];
int x=0;
String stg;
for (String[] name : names2) {
stg = name[1]+" - "+name[2]+ " - "+name[3]+" - "+name[4];
stg1[x]=stg;
x++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_list_item_1,
stg1);
this.setListAdapter(adapter);
}
refer this tutorial you will get an idea: http://www.vogella.com/articles/AndroidSQLite/article.html
you will need to create an Database class instance in your Activity or ListActivity to access getAllCart as
public class TempActivity extends Activity {
DatabaseHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = new DatabaseHandler(TempActivity.this);
// Reading all Carts
List<Cart> Carts = db.getAllCart(); //<< get all Cart details here
//... your code here..
and for showing Carts ArrayList values in ListView you will need to create an Custom Adapter for Adding all items in ListView rows .
for Create ListView with Custom Adapter you can view these tutorials :
Customizing Android ListView Items with Custom ArrayAdapter
Android ListView example

how to show my contacts database value in my spinner?

In my layout xml I have a spinner and in my java I have a database with contacts and some values on it so I want to know how I send or put these values from the database in the spinner so when I click it, it selects the contact, any example of code?
Get the contacts details from the database first.
You can find a sample code for database concept at http://codinglookseasy.blogspot.in/2012/08/sqlite-database.html .
Next from the above sample you may have got ArrayList of objects and set the contact names in the spinner using a
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
Where list here may be the data from your ArrayList from the database. (store a specific field that you want to display from the database into this list).
Get the item selected using
spinner2.getSelectedItem()
which gives the item selected and get the data using from the ArrayList that you got from the database
Just try
//Initialize the spinner view
Spinner spinnerContact = (Spinnner) findViewById(R.id.spinner);
//Initialise List Variable
List<String> contactsList = databaseObj.getContacts;
// Create and Implement Adapter for spinner
ArrayAdapter<String> contactAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, contactsList );
//set drop down view for spinner
contactAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//set adapter for spinner
spinnerContact.setAdapter(contactAdapter);
//select the item in spinner defaultly
spinnerContact.setSelection(position);
//get Selected Item Text from the spinner
spinnerContact.getSelectedItem();
Consider you in main Activty
public class MainActivity extends Activity {
private List<String> contactList;
private Spinner spinnerComp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinnerdemo);
spinnerComp= (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, getContacts());
adapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerComp.setAdapter(adapter);
spinnerComp.setSelection(0);
}
Now getContacts() containsas follows :
// get Contact Names
private List<String> getContacts() {
// get Contacts
List<Contact> contacts = DBHelper.getContacts();
List<String> contactNames = null;
if (contacts.size() != 0) {
contactNames = new ArrayList<String>();
for (Contact contact : Contacts) {
String contactName = contact.getName();
contactNames.add(contactName);
}
}
return contactNames;
}
In DbHelper.java
public List<Contact> getAllContacts() {
String sql = "SELECT * FROM " + Table.CONTACT + " ORDER BY " +
Contact.Column.NAME + " ASC";
List<Contact> contacts = new ArrayList<Contact>();
Cursor cursor = database.rawQuery(sql, null);
while(cursor.moveToNext()) {
Contact contact = getContactFromCursor(cursor);
if(Contact != null) {
contacts.add(Contact);
}
}
cursor.close();
return contacts;
}
private Contact getContactFromCursor(Cursor cursor) {
long id = cursor.getLong(cursor.getColumnIndex(Contact.Column.ID));
String name = cursor.getString(cursor.getColumnIndex(Contact.Column.NAME));
long phoneNumber = cursor.getLong(cursor.getColumnIndex(Contact.Column.DATE_OF_BIRTH));
Contact Contact = new Contact(name, phoneNumber);
Contact.setId(id);
return Contact;
}

Categories

Resources