I have a spinner and a database so when i click the spinner i want to show the value(name) of the contacts in it but in a simple code. so they are separetated javas and xml layouts the spinner is in the (Novamensagem.java novamensagem.xml) and the contacs database is in the (Adicionarcontato.java adicionarcontato.xml) if you can specify and simply the code is better, thanks
final TextView spinnerContato = (TextView) findViewById(R.id.spinner);
String[] campos = new String[] {"nome", "telefone"};
Cursor c = db.query("contatos", campos, null, null, null, null, null);
c.moveToFirst();
String lista = "";
if(c.getCount() > 0) {
while(true) {
lista = lista + c.getString(c.getColumnIndex("nome")).toString() + "";
if(!c.moveToNext()) break;
}
spinnerContato.setText(lista);
}
thats the code but it gives the erros (more explained in comments)
//
the entire code:
ArrayList<String>() list = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.novamensagem);
db = openOrCreateDatabase("banco.db", Context.MODE_WORLD_WRITEABLE, null);
SalvaMensagem();
//Data e Hora
setCurrentDateOnView();
addListenerOnButton();
setCurrentTimeOnView();
addListenerOnButton2();
//Spinner
DadosSpinner();
}
private void DadosSpinner() {
// TODO Auto-generated method stub
final TextView spinnerContato = (TextView) findViewById(R.id.spinner);
String[] campos = new String[] {"nome", "telefone"};
list = new ArrayList<String>();
Cursor c = db.query("contatos", campos, null, null, null, null, null);
c.moveToFirst();
String lista = "";
if(c.getCount() > 0) {
while(true) {
list.add(c.getString(c.getColumnIndex("nome")).toString());
if(!c.moveToNext()) break;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}`
there is.
Check this
list = new ArrayList<String>();
Cursor c = db.query("contatos", campos, null, null, null, null, null);
c.moveToFirst();
String lista = "";
if(c.getCount() > 0) {
while(true) {
list.add(c.getString(c.getColumnIndex("nome")).toString());
if(!c.moveToNext()) break;
}
}
This helps you to get an arrayList of items.
Next do this
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Be back if you have any issues
To load the spinner data from SQLite database you have to:
Read the contacts from database and save it into the list (for example)
Create an adapter for the spinner
Method would look like this:
private void loadSpinnerData()
{
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<String> contacts = db.getAllContacts();
// 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);
}
And getAllContacts() method will return all the contacts:
public List<String> getAllConatcts(){
List<String> contacts = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
contacts.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning contatcs
return contacts;
}
For more information check this tutorial: http://www.androidhive.info/2012/06/android-populating-spinner-data-from-sqlite-database/
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 need help in showing two values from database in my listview which I am populating through array Adapter but default array Adapter shows only 1 value I want to show two values. Below is my code of how i am populating the array adapter through db.
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
final Cursor cursor = db.query(TaskContract.TaskEntry.TABLE,
new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
mAdapter = new ArrayAdapter<>(this,
R.layout.item_todo,
R.id.task_title,
taskList);
mTaskListView.setAdapter(mAdapter);
cursor.close();
db.close();
}
Try below code :
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
final Cursor cursor = db.query(TaskContract.TaskEntry.TABLE,
new String[]{TaskContract.TaskEntry._ID, TaskContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
if(cursor.getCount()>0 && cursor.moveToFirst()){
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
}
mAdapter = new ArrayAdapter<>(this,
R.layout.item_todo,
R.id.task_title,
taskList);
mTaskListView.setAdapter(mAdapter);
cursor.close();
db.close();
}
I have a little issue that I don't know how to address.
I have a Cursor that gets data from my data base it looks like this:
public Cursor getAllData(){
int id;
SQLiteDatabase DB = this.getWritableDatabase();
String dateTime = Helper.getCurrentDate();
String date = dateTime.substring(0, 10);
String date_to_look = date.substring(0, 10);
String sql = "SELECT h.product_id, h.qty, h.date_time, p.product " +
" FROM product_history h " +
" LEFT JOIN products p ON (p.rowid = h.product_id) ";
Cursor res = DB.rawQuery(sql, null);
return res;
}
Then on my activity I'm using the following method:
public void populateListView() {
Cursor cursordata = myDb.getAllData();
String productname = cursordata.getString(cursordata.getColumnIndex("product"));
String [] products = {productname};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, products);
ListView listviewman = (ListView)findViewById(R.id.listviewman);
listviewman.setAdapter(adapter);
}
Execute it with onclick:
public void shine(View v){
Button shine = (Button)findViewById(R.id.shine);
populateListView();
}
What am I doing wrong?
Edit:
Shows last row from the table only.
public void populateListView() {
Cursor cursordata = myDb.getAllData();
if (cursordata.moveToFirst()) {
do {
String productname = cursordata.getString((cursordata.getColumnIndex("product")));
String [] products = {productname};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, products);
ListView listviewman = (ListView)findViewById(R.id.listviewman);
listviewman.setAdapter(adapter);
} while (cursordata.moveToNext());
}
Sahil here is the updated version of your suggestion which i use, it's not working:
public void populateListView() {
Cursor cursordata = myDb.getAllData();
List<String> li_records=new ArrayList<String>;
if (cursordata.moveToFirst()) {
do {
String productname = cursordata.getString((cursordata.getColumnIndex("product")));
String[] products = {productname};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, products);
ListView listviewman = (ListView) findViewById(R.id.listviewman);
listviewman.setAdapter(adapter);
li_records.add(productname);
} while (cursordata.moveToNext());
}
String[] products=li_records.toArray();
}
try this it will work fine:
public void populateListView() {
Cursor cursordata = myDb.getAllData();
ArrayList<String> products = new ArrayList<>();
if (cursordata.moveToFirst()) {
do {
String productname = cursordata.getString((cursordata.getColumnIndex("product")));
products.add(productname);
} while (cursordata.moveToNext());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, products);
ListView listviewman = (ListView)findViewById(R.id.listviewman);
listviewman.setAdapter(adapter);
}
Try to put
cursordata.moveToFirst()
after
List<String> li_records=new ArrayList<String>;
Cursor cursordata = myDb.getAllData();
use do while loop like this,
// looping through all rows and adding to list
if (cursordata.moveToFirst()) {
do {
String productname = c.getString((c.getColumnIndex("product")));
li_records.add(productname);
} while (cursordata.moveToNext());
}
String[] products=li_records.toArray();
use this array in your adapter
I'm relatively new to Android and I was making a To-Do List application. I have a database containing a column of tasks. How can I put these tasks into an ArrayList and display it ?
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.query(TaskContract.TABLE, new String[]{TaskContract.Columns._ID,TaskContract.Columns.TASK}, null, null, null, null, null);
arrayListToDo = new ArrayList<String>();
arrayAdapterToDo = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayListToDo);
ListView listViewToDo = (ListView) findViewById(R.id.listViewToDo);
listViewToDo.setAdapter(arrayAdapterToDo);
Try this code
while (cursor.moveToNext()) {
arrayListToDo.add(cursor.getString(cursor.getColumnIndex("Your column name")));
}
You can get the data in Array list :-
ArrayList<String> arrayListToDo= new ArrayList<String>();
//your query will returns cursor
if (cursor.moveToFirst()) {
do {
arrayListToDo.add(get you string from cursor);
} while (cursor.moveToNext());
}
now add this aray list to your Adapter.
get list data from database this is only overview
ArrayList<String> data = databaseObject.GetList();
ListView listViewToDo = (ListView) findViewById(R.id.listViewToDo);
arrayAdapterToDo = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
listViewToDo.setAdapter(arrayAdapterToDo);
ArrayList<String> GetList()
{
ArrayList<String> arrayListtemp= new ArrayList<String>();
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.query(TaskContract.TABLE, new String[]{TaskContract.Columns._ID,TaskContract.Columns.TASK}, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
arrayListtemp.add("");// added your table value from database
} while (cursor.moveToNext());
}
return arrayListtemp;
}
The problem is i inserted only two rows but on execution it enters into infinite loop and repeatedily showing the same data..Any kind of help would be appreciated
Here is my code.
This is my databse class (i.e DbAdapter)
public Cursor getAllRows() {
String[]columns = new String[]{ KEY_MODEL,KEY_BRAND, KEY_PRICE};
Cursor c = db.query(TABLE_LAPTOPS, columns, null, null, null, null, null);
if (c != null) {
c.moveToLast();
}
return c;
}
This is my main class (i.e Laptops)
DbAdapter obj = new DbAdapter(this);
obj.open();
obj.insertRow("Dell1", "Dell", 345);
obj.insertRow("Hp1", "HP", 546);
obj.close();
obj.open();
Cursor c1 = obj.getAllRows();
try{
if(c1 != null){
ListView empListView = (ListView)findViewById(R.id.listView1);
ArrayList<String> data1 = new ArrayList<String>();
for(c1.moveToFirst();!c1.isAfterLast();c1.moveToNext())
{
Toast.makeText(getApplicationContext(), c1.getString(0), Toast.LENGTH_LONG).show();
}
//empListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data1));
}}catch(SQLException e){
e.printStackTrace();
}
obj.close();
c.moveToLast();
here is the issue
c.moveToFirst();
try this..
Try with Like This
listView = (ListView) rootView.findViewById(R.id.Assignment_VM_List);
AssignmentDatabaseConnector dao = new AssignmentDatabaseConnector(getActivity());
List<AssignmentPojo> assignments = dao.getAllAssignmentList();
AssignmentCustomAdapter assignmentCustomAdapter = new AssignmentCustomAdapter(getActivity(),
assignments, this);
listView.setAdapter(assignmentCustomAdapter);
AssignmentDatabaseConnector :
public List<AssignmentPojo> getAllAssignmentList() {
open();
List<AssignmentPojo> assignmentList = new ArrayList<AssignmentPojo>();
// Select All Query
String selectQuery = "SELECT * FROM Assignment";
Cursor cursor = database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) { // ##Your Main Issue is Here ##
do {
AssignmentPojo assignment = new AssignmentPojo();
assignment.setAssign_Id(cursor.getString(0));
assignment.setAssign_Course(cursor.getString(1));
// Adding contact to list
assignmentList.add(assignment);
} while (cursor.moveToNext());
}
cursor.close();
database.close();
// return contact list
return assignmentList;
}
This is just a sample code you can utilize this code according to your requirements