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;
}
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);
Well I have an arraylist from my sqlite data. And I'm setting this arraylist on my arrayadapter of my spinner.
Here's how I do it:
public ArrayList<AttendantModelNames> getAllAttendantNames() {
ArrayList<AttendantModelNames> attendantModelArrayList = new ArrayList<>();
hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("SELECT * FROM " + TABLE_ATTENDANTS, null);
res.moveToFirst();
while (!res.isAfterLast()) {
AttendantModelNames l_att = new AttendantModelNames();
l_att.setname(res.getString(res
.getColumnIndex(KEY_NAME)));
attendantModelArrayList.add(l_att);
res.moveToNext();
}
Log.d(TAG, attendantModelArrayList.toString());
res.close();
return attendantModelArrayList;
}
Then my AttendantModelNames POJO:
public class AttendantModelNames {
String name;
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
}
Then on my spinner:
private void setSpinner() {
spinner = (Spinner) findViewById(com.duka.R.id.spinner_toolbar);
ArrayList<AttendantModelNames> modelArrayList = ah.getAllAttendantNames();
ArrayAdapter<AttendantModelNames> dataAdapter =
new ArrayAdapter<AttendantModelNames>(this, android.R.layout.simple_spinner_item, modelArrayList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
int selectionPosition= dataAdapter.getPosition(modelArrayList.get(position).getname());
spinner.setSelection(selectionPosition);
I tried setting this but doesn't seem to work, says:
get(int) in arraylist cannot be applied to (java.lang.String) on
position
Any suggestions will be appreciated.
This is how i resolved my issue:
I started out by returning an list of type string:
public List<String> getAllAttendantNames() {
List<String> list = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ATTENDANTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);//selectQuery,selectedArguments
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(2));//adding 2nd column data
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
// returning lables
return list;
}
Then set up spinner:
private void loadSpinnerData() {
List<String> labels = ah.getAllAttendantNames();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, labels);
// 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);
int spinnerPosition = dataAdapter.getPosition(s_attname);
Log.d("spinner_set_selection", s_attname + spinnerPosition);
spinner.setSelection(spinnerPosition);
}
And ofcourse onCreate():
spinner = (Spinner) findViewById(R.id.spinner);
// Loading spinner data from database
loadSpinnerData();
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.
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!
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