In my android app, i m trying show a list through list adapter and the data comes from SQLite db. However the list items are not showing up , though everything is fine , i think! .
This is my code for showing list
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.store_list_activity);
float storeId = 1;
//Storedb is my data adapter class of SQLite
StoreDb storelist = new StoreDb(this);
storelist.open();
ArrayList arraylist= storelist.getStoreName(storeId);
adapter= new ArrayAdapter<String>(this, R.layout.store_list_style, arraylist);
medicine_List= (ListView) findViewById (R.id.list);
medicine_List.setAdapter(adapter);
medicine_List.setOnItemClickListener(this);
}
And this is the method for reading data from SQLite!
public ArrayList getStoreName(long storeId) {
ArrayList<String> array_list = new ArrayList<String>();
String[] column2 = new String[] { AREA_PREV_ID, STORE_NAME };
Cursor res = ourDatabase.query(DATABASE_TABLE2, column2, AREA_PREV_ID + "=" + storeId, null, null, null, null);
int istore = res.getColumnIndex(STORE_NAME);
if (res != null) {
res.moveToFirst();
while(res.isAfterLast() == false){
String s = res.getString(istore);
array_list.add(s);
res.moveToNext();
}
}
return array_list;
}
Can anyone help what m i doing wrong here!Thanks in advance
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);
I'm trying to get some data from a DB and display in a listview, but they logcat say Make sure the Cursor is initialized correctly before accessing data from it. This is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cotizacionescolumna);
lvCotizacion = (ListView)findViewById(R.id.lista_cotizaciones);
list_cotizaciones = new ArrayList<String>();
llenarLista();
eventos();
}
public void llenarLista(){
CotiCadSqlite db = new CotiCadSqlite(CotizacionesColumnnaActivity.this);
Cursor c = db.obtenerNombresColumna();
if(c.moveToFirst()){
do{
columna = c.getString(1);
list_cotizaciones.add(columna);
}while (c.moveToNext());
}
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list_cotizaciones);
lvCotizacion.setAdapter(adapter);
}
columna = c.getString(1);
to
c.getString(c.getColumnIndex(1))
as well
if (null != c) {
if (c.moveToFirst()) {
do {
//your code goes here
} while (c.moveToNext());
}
c.close();
try like this,
Cursor c = helper.DatabaseMethod();// retrive data
c.moveToFirst();
while (c.isAfterLast() == false)
{
String dataSaved = c.getString(c.getColumnIndex(DataBaseHelper.KEY_EMAIL));//your column index name
list_cotizaciones.add(dataSaved );
c.moveToNext();
}
c.close();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list_cotizaciones);
lvCotizacion.setAdapter(adapter);
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 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
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/