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!
Related
Hi guys i have trouble to bind the existing data from sqlite to spinner. Do i have to apply arraylist ? If so how do i do it? Please help me i'm still new and this is for my project.
this is how the data taken from database :
public Cursor alldata()
{
ArrayList<String> values = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("Select * from shop", null);
return cursor;
}
this is the coding that supposedly to receive the data and show it on spinner but i have no idea to do it :
SpListofShop = (Spinner) findViewById(R.id.SpListofShop);
Cursor cursor = db.alldata();
if(cursor.getCount()==0)
{
Toast.makeText(getApplicationContext(), "NO DATA", Toast.LENGTH_SHORT).show();
}
else
{
while(cursor.moveToNext())
{
}
}
i really hope any of you can help me i'm too desperate
Coding to call the public arraylist function
this is the coding to call the public arraylist in databasehelper.java :
Spinner SpListofShop = findViewById(R.id.SpListofShop);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, db.alldata());
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);
SpListofShop.setAdapter(adapter);
1.change alldata as follows:
public ArrayList<String> alldata()
{
ArrayList<String> values = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("Select * from shop", null);
for (int i=0;i<cursor.getCount();i++){
values.add(cursor.getString(cursor.getColumnIndex("row_name")));
//edit, change row_name with your row
}
cursor.close();
return values;
}
2.change spinner code like this:
Spinner SpListofShop = findViewById(R.id.SpListofShop);
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, alldata());
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);
SpListofShop.setAdapter(adapter);
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_item);
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.
i want to display data from sqlite to textview,here is my code.What i have dont wrong.It is not displaying the data no error but crashes
main class
private void loadTextViewData()
{
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
List<String> lables = db.getAllLabels();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.test_list_item, lables);
text.setText(??);
}
sql class
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;
}
instead of ArrayAdapter use for example SimpleCursorAdapter (or any subclass of CursorAdapter)
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.
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;
}