Show all database contents in a ListView - android

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);

Related

Android - How can I put database rows into a ListView?

I am trying to view the content of my database by listing it in a ListView. What am i doing wrong? The goal is to load a list of the database data when the page loads after a button click on the homepage.
The XML page simply has a ListView, named "studentList", inside a ScrollView
Java code:
public class edit_student extends AppCompatActivity {
private dbasemanager dBase;
private ListView studentInfoList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_student);
dBase.openReadable();
studentInfoList = (ListView)findViewById(R.id.studentList);
ArrayList<String> dBaseContent = dBase.retrieveRows();
ArrayAdapter<String> arrayAdpt = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, dBaseContent);
studentInfoList.setAdapter(arrayAdpt);
dBase.close();
}
}
This is openReadable() Function:
public dbasemanager openReadable() throws android.database.SQLException {
helper = new SQLHelper(context);
db = helper.getReadableDatabase();
return this;
}
This is the retrieveRows() Function:
public ArrayList<String> retrieveRows() {
ArrayList<String> studentRows = new ArrayList<>();
String[] columns = new String[] {"sid", "first_name", "last_name"};
Cursor cursor = db.query(Table_Name, columns, null, null, null, null, null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
studentRows.add(cursor.getString(0) + ", " + cursor.getString(1)
+ ", " + cursor.getString(2));
cursor.moveToNext();
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return studentRows;
}
Logcat:
There is a null pointer in line 17.
You need to construct databasemanager object before call it
public class edit_student extends AppCompatActivity {
private dbasemanager dBase;
private ListView studentInfoList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_student);
// construct databasemanager
dBase = new dbasemanager(...);
dBase.openReadable();
studentInfoList = (ListView)findViewById(R.id.studentList);
ArrayList<String> dBaseContent = dBase.retrieveRows();
ArrayAdapter<String> arrayAdpt = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, dBaseContent);
studentInfoList.setAdapter(arrayAdpt);
dBase.close();
}
}
BTW, I recommend you to use java code conventions to name classes.
For example: edit_student should be editStudent and dbasemanager should be DBManager or DbManager.

Android SQLite get value from column

I have a column ShopName, and another column called LocationCode, if the LocationCode equals to "SKP", the corresponding ShopName will be added to an array, my question is, how can I do that?
I got something like this:
public List<String> getQuotes() {
String WhiteFarm = "WhiteFarm";
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM WhereToEat WHERE 'LocationCode' = " + WhiteFarm, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return list;
}
And another class like this:
public class DatabaseGrabber extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selection_main);
final TextView Shop_name = (TextView)findViewById(R.id.ShopName);
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
databaseAccess.open();
final List<String> ShopName = databaseAccess.getQuotes();
databaseAccess.close();
Button StartDraw = (Button)findViewById(R.id.draw_start);
StartDraw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Collections.shuffle(ShopName);
String random = ShopName.get(0);
Shop_name.setText(random);
}
});
}
}
If your LocationCode contains a String (or TEXT for SQLite) type of data then your value should be enclosed in a single quote as shown in the code below:
Cursor cursor = database.rawQuery("SELECT * FROM WhereToEat WHERE LocationCode = " + "'" + WhiteFarm "'", null);

List items not showing when reading data from SQLite db

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

how to re-open or close SQLitedatabase?

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

SQLite to ListView(androidhive's version)

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

Categories

Resources