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
Related
I want to Show all database contents in a List View in Android Studio, I expect to see 3 rows that each row contains "name, family and ID" , but I see a comlex of package name and some other characters as follws:
com.google.www.hmdbtest01.Person#529e71b4
com.google.www.hmdbtest01.Person#529e7238
com.google.www.hmdbtest01.Person#529e7298
if I have more rows in my database, I will see more lines like above in the output.
my codes are as follow:
public class ListOfData extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_data);
ListView list = findViewById(R.id.list1);
HmDbManager01 db= new HmDbManager01(this);
ArrayList personList = db.getAll();
ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
android.R.layout.simple_list_item_1, personList);
list.setAdapter(arrayList);
}
}
db.getAll() is as follows:
public ArrayList<Person> getAll(){
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor= sqLiteDatabase.rawQuery("SELECT * FROM tbl_person", null);
cursor.moveToFirst();
ArrayList<Person> allData = new ArrayList<>();
if(cursor.getCount() > 0){
while (!cursor.isAfterLast()){
Person p1 = new Person();
p1.pID=cursor.getString(0);
p1.pName=cursor.getString(1);
p1.pFamily=cursor.getString(2);
allData.add(p1);
cursor.moveToNext();
}
}
cursor.close();
sqLiteDatabase.close();
return allData;
}
and, this is Person:
package com.google.www.hmdbtest01;
public class Person {
public String pID;
public String pName;
public String pFamily;
}
Let me know your comments on this problem.
arrayListAdapter will convert your personList to list of string
change like it:
ArrayList<String> persons = new ArrayList<String>();
personList.forEach(personModel -> {
persons.add(personModel.name + " " + personModel.lastName + " " + personModel.id);
});
ArrayAdapter<ArrayList> arrayList = new ArrayAdapter<ArrayList>(this,
android.R.layout.simple_list_item_1, persons);
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 gone through many pages for the same problem but i still cant find an solution for this !!
I'm getting error "attempt to re-open an already closed objectSQLiteDatabase".
public List getData(){
List list = new ArrayList();
Cursor c = db.rawQuery("SELECT * FROM Table",null );
int i = cursor.getColumnIndex(KEY1);
int ii = cursor.getColumnIndex(KEY2);
int iii = cursor.getColumnIndex(KEY3);
int inum = cursor.getColumnIndex(KEY4);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
String student = cursor.getString(inum) + "\t" +cursor.getString(i) +"\t" +cursor.getString(ii) + "\t" +cursor.getString(iii);
list.add(student);
cursor.moveToPrevious();
}
}
public List getInfo()
{
List list = new ArrayList();
Cursor c = db.rawQuery("SELECT * FROM Table where name = ?",new string[]{"android"} );
int i = cursor.getColumnIndex(KEY1);
int ii = cursor.getColumnIndex(KEY2);
int iii = cursor.getColumnIndex(KEY3);
int inum = cursor.getColumnIndex(KEY4);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
String student = cursor.getString(inum) + "\t" +cursor.getString(i) +"\t" +cursor.getString(ii) + "\t" +cursor.getString(iii);
list.add(student);
cursor.moveToPrevious();
}
Im getting this values as list and putting it in list
ListView list = (ListView) findViewById(R.id.list);
ListView list1 = (ListView) findViewById(R.id.list1);
List val = info.getData();
List val1 - info.getInfo();
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,val);
ArrayAdapter adapter1 = new ArrayAdapter(this,android.R.layout.simple_list_item_1,val1);
list.setAdapter(adapter);
list1.setAdapter(adapter1);
info.close()
First of all where are you creating database?
You should use a class that extends SQLiteOpenHelper
eg:
public class MySQLiteHelper extends SQLiteOpenHelper {
//here you create your database and tables
}
To open/close database
// Database Fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
More info/example here:
http://www.vogella.com/tutorials/AndroidSQLite/article.html
Please check what problem with this .I am trying to retrive all records in my table (contains 11 records with 3 columns "name","address","city") but my code showing only one i.e last inserted record on my screen. but i need to display all records.
public void readData(View v)
{
DatabaseClass mydb = new DatabaseClass(this);
SQLiteDatabase readdata = mydb.getReadableDatabase();
TextView tv = (TextView)findViewById(R.id.readtext);
Cursor c = readdata.rawQuery("select * from mylistdata", null);
int[] elementId = {R.id.textView1, R.id.textView2, R.id.textView3};
if(c !=null)
{
c.moveToFirst();
while(c.isAfterLast() == false)
{
listData = new ArrayList<GenericListItem>();
String name = c.getString(c.getColumnIndex(DatabaseClass.NAME));
String address = c.getString(c.getColumnIndex(DatabaseClass.ADDRESS));
String city = c.getString(c.getColumnIndex(DatabaseClass.CITY));
listData.add(new GenericListItem(new String[]{name,address,city}));
listAdapter = new GenericListAdapter(getApplicationContext(), R.layout.list_layout, listData, elementId);
result.setAdapter(listAdapter);
c.moveToNext();
}
}
Initialize listData ArrayList outside from While loop as:
c.moveToFirst();
listData = new ArrayList<GenericListItem>();
while(c.isAfterLast() == false)
{
// add value here to listData
c.moveToNext();
}
// set listData datasource to GenericListAdapter here
listAdapter = new GenericListAdapter(getApplicationContext(),
R.layout.list_layout, listData, elementId);
result.setAdapter(listAdapter);
It looks like the problem is that you are re-creating your list each time through the loop. Try this:
listData = new ArrayList<GenericListItem>(); //moved out of loop
while(c.isAfterLast() == false)
{
String name = c.getString(c.getColumnIndex(DatabaseClass.NAME));
String address = c.getString(c.getColumnIndex(DatabaseClass.ADDRESS));
String city = c.getString(c.getColumnIndex(DatabaseClass.CITY));
listData.add(new GenericListItem(new String[]{name,address,city}));
listAdapter = new GenericListAdapter(getApplicationContext(), R.layout.list_layout, listData, elementId);
c.moveToNext();
}
result.setAdapter(listAdapter); // moved out of loop
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/