android display data from database using listview - android

I am trying to make simple android app where the user enter his information and then save it in the database and display the user info using listview. I have three java files: DBHelper.java, MainActivity.java and userInfo.java.
(MainActivity.java) is where the user enters his name and email.
(DBHelper.java) is where the database is created to save the user info.
(userInfo.java) is where the user info can be displayed.
in my app I successfully displayed the data from database using textview, and my question is how I can display the data from database using listview.
updated:
this is the getData() method from DBHelper.java file:
public List<Person> getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ID2, KEY_NAME, KEY_EMAIL};
Cursor c = ourDbase.query(TABLE_SCORE, columns, null, null, null, null, null + " DESC");
List<Person> people = new ArrayList<Person>();
int iRow = c.getColumnIndex(KEY_ID);
int iName = c.getColumnIndex(KEY_NAME);
int iEmail= c.getColumnIndex(KEY_EMAIL);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
Person p = new Person();
p.setEmail(c.getString(iEmail));
//set other info, like id, name
people.add(person);
}
return people;
}
here is the Person class:
public class Person {
private int ID;
private String NAME;
private String EMAIL;
public Person()
{
ID=0;
NAME="";
EMAIL="";
}
public Person(String qNAME, int qEMAIL) {
NAME = qNAME;
EMAIL= qEMAIL;
}
public int getID()
{
return ID;
}
public String getNAME() {
return NAME;
}
public int getEMAIL() {
return EMAIL;
}
public void setID(int id)
{
ID=id;
}
public void setNAME(String qNAME) {
NAME = qNAME;
}
public void setSCORE(int qEMAIL) {
EMAIL= qEMAIL;
}
}
and this is the code where I get the data from database and set it in textview from userInfo.java:
DbHelper userInfo = new DbHelper(this);
userInfo .open();
String data = userInfo .getData();
userInfo .close();
tv.setText(data);

how I can display the data from database using listview.
Since you dont provide any code about the listview and its adapter, i assume you dont know where to start.
You should create a listview, either with custom-created adapter or basic adapter (from android). After that, add the data from the database to your listview's adapter and use notifyDataSetChanged() to make sure the data is refreshed on the listview.
Simple tutorial : http://androidexample.com/Create_A_Simple_Listview_-_Android_Example/index.php?view=article_discription&aid=65&aaid=90
In-depth (recommended) tutorial : http://www.vogella.com/tutorials/AndroidListView/article.html

Related

Store SQLite query result in a String array

How can I save a query result in a String array?
The query is simple, it's got only one column i.e.:
SELECT NAME FROM MYTABLE
What I want is to store the ids in a String array so I can show them as clickable items in a ListView
Try this
String selectQuery = "SELECT * FROM table";
try {
Cursor cursor = db.rawQuery(selectQuery, null);
ArrayList<String> ids = new ArrayList<>();
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
String id = cursor.getString(cursor.getColumnIndex(KEY_ID));
ids.add(id);
} while (cursor.moveToNext());
}
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
Assuming you've already executed your query against a SQLiteDatabase object, and received a Cursor in return, you can iterate through the cursor and save the value of each row to a String[] array like so:
String[] names;
if (cursor.moveToFirst()) {
names = new String[cursor.getCount()];
int colIndex = cursor.getColumnIndex("NAME");
do {
names[cursor.getPosition()] = cursor.getString(colIndex);
} while (cursor.moveToNext());
}
Keep in mind that names will be null if no rows are returned, so make sure you do a null check.
create following method in SQLiteOpenHelper class
public List<String> getAllNames() {
List<String> retData = new ArrayList<String>();
String selectQuery = "SELECT NAME FROM MYTABLE";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
retData.add(cursor.getString(0));
} while (cursor.moveToNext());
}
return retData;
}
then assign this returned list to adapter
The issue with listing id's is that they tend to be meaningless to an end user. Really you want to display user meaningful data, e.g. a name, but to then be able to access the respective id to then efficiently act on a selection from the list presented to a user.
Using an ArrayList is frequently the cause of much frustration, as the list shows what is required but it's then found to be of little use when attempting to use the list beyond displaying data e.g. selecting an item to then do something such as delete or update (if the value is unique within the database it can be used).
As such an ArrayList<your_object> rather then an ArrayList<String> is generally more viable as the source of the List; a Cursor Adapter can also be used as data from the underlying row is easily obtained.
However, there is an issue, unless a Custom Array Adapter is utilised, when using an ArrayList in that the ArrayAdapter class uses the toString method of the object to retrieve the data that is displayed. The simple fix is to provide a suitable toString method in the object, if you don't you will get something long the lines of “SomeType#2f92e0f4”.
Example showing all 3
In the following working example :-
the database (mydb) has 1 table named mytable which has two columns _id (Note must be _id for a CursorAdapter)
There are 3 methods to get the 3 types of list (named accordingly) :-
getAllAsStringArrayList (gets ArrayList)
getAllAsMyTableObjectArrayList (gets ArrayList). Note uses the MyTableObject class (see note in class re overriding the default toString method)
getAllAsCursor
The App, when run, will have 3 lists, the left based upon the first ArrayList, the middle based upon the ArrayList and the last based upon the Cursor.
Clicking an item in any of the lists displays the respective name along with attempts to get the id.
The ArrayList, Left List, fails in this aspect as it can only get the position (i.e. the 4th parameter passed to the listener is the same value as the position).
The ArrayList, middle List, when getting the id from the object (which is retrieved via the getItem(position) method of the Adapter) successfully retrieves the correct id, the 4th parameter is the same as the position, and should not be used.
The Cursor, Right List, retrieves the correct id both via the Cursor and the 4th parameter.
The Code
MyTableObject.java :-
public class MyTableObject {
private long id;
private String name;
public MyTableObject(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*
NOTE toString method returns just the name
*/
#Override
public String toString() {
return name;
}
}
DatabaseHelper.java :-
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TB_MYTABLE = "mytable";
public static final String COl_MYTABLE_ID = BaseColumns._ID; //<<<< use standard android id column name
public static final String COL_MYTABLE_NAME = "_name";
private static final String mytable_crtsql =
"CREATE TABLE IF NOT EXISTS " + TB_MYTABLE +
"(" +
COl_MYTABLE_ID + " INTEGER PRIMARY KEY, " +
COL_MYTABLE_NAME + " TEXT " +
")";
SQLiteDatabase mDB;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(mytable_crtsql);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long addRow(String name) {
ContentValues cv = new ContentValues();
cv.put(COL_MYTABLE_NAME,name);
return mDB.insert(TB_MYTABLE,null,cv);
}
public ArrayList<String> getAllAsStringArrayList() {
ArrayList<String> rv = new ArrayList<>();
Cursor csr = mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
while (csr.moveToNext()) {
rv.add(csr.getString(csr.getColumnIndex(COL_MYTABLE_NAME)));
}
csr.close();
return rv;
}
public ArrayList<MyTableObject> getAllAsMyTableObjectArrayList() {
ArrayList<MyTableObject> rv = new ArrayList<>();
Cursor csr = mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
while (csr.moveToNext()) {
rv.add(new MyTableObject(
csr.getLong(csr.getColumnIndex(COl_MYTABLE_ID)),
csr.getString(csr.getColumnIndex(COL_MYTABLE_NAME))
)
);
}
csr.close();
return rv;
}
public Cursor getAllAsCursor() {
return mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDBHlpr;
ListView mListView01,mListVeiw02,mListView03;
ArrayAdapter<String> mAdapterStringArrayList;
ArrayAdapter<MyTableObject> mAdapterMyTableObjectArrayList;
SimpleCursorAdapter mAdapterCursor;
ArrayList<String> mMyTableListAsStrings;
ArrayList<MyTableObject> mMyTableAsObjects;
Cursor mMyTableListAsCursor;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mListView01 = this.findViewById(R.id.listview01);
mListVeiw02 = this.findViewById(R.id.listview02);
mListView03 = this.findViewById(R.id.listview03);
mDBHlpr = new DatabaseHelper(this);
mDBHlpr.addRow("Fred");
mDBHlpr.addRow("Bert");
mDBHlpr.addRow("Harry");
mDBHlpr.addRow("Fred");
//String Array List
mMyTableListAsStrings = mDBHlpr.getAllAsStringArrayList();
mAdapterStringArrayList = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
mMyTableListAsStrings
);
mListView01.setAdapter(mAdapterStringArrayList);
//Object Array List
mMyTableAsObjects = mDBHlpr.getAllAsMyTableObjectArrayList();
mAdapterMyTableObjectArrayList = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
mMyTableAsObjects
);
mListVeiw02.setAdapter(mAdapterMyTableObjectArrayList);
// Cursor
mMyTableListAsCursor = mDBHlpr.getAllAsCursor();
mAdapterCursor = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mMyTableListAsCursor,
new String[]{DatabaseHelper.COL_MYTABLE_NAME},
new int[]{android.R.id.text1},
0
);
mListView03.setAdapter(mAdapterCursor);
mListView01.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = mAdapterStringArrayList.getItem(position);
Toast.makeText(
mContext,
"Name is " + name +
". ID is " + String.valueOf(id) +
" (note may not match)",
Toast.LENGTH_SHORT
).show();
}
});
mListVeiw02.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
MyTableObject mytable = mAdapterMyTableObjectArrayList.getItem(position);
String name = mytable.getName();
long id_in_object = mytable.getId();
Toast.makeText(
mContext,
"Name is " + name +
". ID from object is " + String.valueOf(id_in_object) +
". ID from adapter is " + String.valueOf(id),
Toast.LENGTH_SHORT
).show();
}
});
mListView03.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Cursor csr = mAdapterCursor.getCursor(); // already positioned
String name = csr.getString(csr.getColumnIndex(DatabaseHelper.COL_MYTABLE_NAME));
long id_in_cursor = csr.getLong(csr.getColumnIndex(DatabaseHelper.COl_MYTABLE_ID));
Toast.makeText(
mContext,
"Name is " + name +
". ID from object is " + String.valueOf(id_in_cursor) +
". ID from adapter is " + String.valueOf(id),
Toast.LENGTH_SHORT
).show();
}
});
}
}

What to use to store the rows after reading from table in android

What is the best way to save data read from SQLiteDatabase Android, and access them using row number or column name?
Hi Below is my code that I am using to fetch the data but I want to store the rows in some kind of dataset so that i can fetch the data using column number or name . I want to dynamically show these data in a grid in android.
MyDatabaseSQLHelper myDatabaseSQLHelper = new MyDatabaseSQLHelper(this);
SQLiteDatabase mySQLiteDatabase = myDatabaseSQLHelper.getReadableDatabase();
String[] projection = {
Items._ID,
Items.COL_ITEM_NAME,
Items.COL_ITEM_PRICE,
Items.COL_ITEM_QUANTITY,
Items.COL_ITEM_AMOUNT
};
Cursor cursor = mySQLiteDatabase.query(Items.TABLE_NAME,projection,null,null,null,null,null);
To store all rows fetch from database you can store it in Array list of type modal class. for you your modal class could be like this
ItemBeen.java
public class ItemBeen {
String id,itemName,itemPrice,itemQty,itemAmount;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemPrice() {
return itemPrice;
}
public void setItemPrice(String itemPrice) {
this.itemPrice = itemPrice;
}
public String getItemQty() {
return itemQty;
}
public void setItemQty(String itemQty) {
this.itemQty = itemQty;
}
public String getItemAmount() {
return itemAmount;
}
public void setItemAmount(String itemAmount) {
this.itemAmount = itemAmount;
}
}
then now in your class make method for get data from database and it store all record to array list and return that array list , like this.
public ArrayList<ItemBeen> getItemList() {
Cursor cur;
ArrayList<itemBeen> itemList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
cur = db.query(Items.TABLE_NAME.TBL_ITEM, projection, null, null, null, null, null);
if (cur != null) {
if (cur.moveToFirst()) {
do {
ItemBeen bean = new ItemBeen();
bean.setId(cur.getString(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ID)));
bean.setItemName(cur.getString(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_NAME)));
bean.setItemPrice(cur.getBlob(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_PRICE)));
bean.setItemQty(cur.getString(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_TQY)));
bean.setItemAmount(cur.getInt(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_AMT)));
itemList.add(bean);
} while (cur.moveToNext());
}
}
return itemList;
}
Now in that class in which you want all item list in that class call this method.declare array list and fetch data.
ArrayList<ItemBeen> itemList = new ArrayList<ItemBeen>();
itemList = DBConstant.dbHelper.getItemList();
and this way in itemList contains all records.

Not able to implement search using existing table in database in android

I am trying to implement search on user input. The serach results will be shown after searching the relevant option from database.
I have made this method to display the results
public Cursor getBooksBySearch(String query) {
// TODO Auto-generated method stub
String[] args={query};
return(getReadableDatabase().rawQuery("SELECT _id,chapter FROM chapters WHERE chapter LIKE '%" + query + "%", args));
}
Here the query is coming from an activity SearchResultAcitvity.java
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
ListView myListView = (ListView)findViewById(R.id.txt_query);
dbBookHelper = new BooklistHelper(this);
ourCursor = dbBookHelper.getBooksBySearch(query);
startManagingCursor(ourCursor);
adapter = new BookAdapter(ourCursor);
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(onListClick);
}
I want to match this coming query string to get the results from my chapter table.
Can I just match the query string m getting in String query = intent.getStringExtra(SearchManager.QUERY) with the data in my database.
Using list view to display.
Please help me in this.
Let me know if you want more information
Thanks in Advance :)
This will return list of data search by keyword
public ArrayList<ObjectType> getSearchData(String keyword)
{
ArrayList<ObjectType> objectTypeList = new ArrayList<ObjectType>();
SQLiteDatabase db = getWritableDatabase();
String checkEntry="SELECT id,firstname,lastname FROM abc_table WHERE firstname like '%"+ keyword +"%'" +" or "+ "p.lastname like '%"+ keyword +"%'";
Cursor cursor = db.rawQuery(checkEntry, null);
try
{
//If entry exist then update
if (cursor.moveToFirst())
{
do
{
ObjectType objectType = new ObjectType();
int PID=cursor.getInt(0);
String fname = cursor.getString(1);
String LastName = cursor.getString(2);
objectType.setFirstName(fname);
objectType.setLastName(LastName);
objectTypeList.add(objectType);
}
while(cursor.moveToNext());
}
}
finally
{
if(cursor != null)
cursor.close();
}
return objectTypeList;
}
ObjectType is class
public class ObjectType {
int id;
String firstName;
String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Hope this ll help you.. :)

Android - SQLite query like MySQL

I have the following to fetch data from android SQLite database
my function in android
public List<String> getMyDetails()
{
List<String> dataList = new ArrayList<String>();
Cursor cursor = myDataBase.rawQuery("SELECT * FROM pic_details WHERE _id=1",null);
if (cursor .moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
dataList.add(name);
} while (cursor.moveToNext());
}
return dataList;
}
In activity calling like this
List<String> piclist= dbHelper. getMyDetails();
Its returning the name of the candidate. But I want to return the entire column of the table something like this in PHP, MySQL
$sql=mysql_query("SELECT * FROM pic_details WHERE _id=1");
$i=0;
$out=array();
while($t=mysql_fetch_array($sql)){
$out[$i]['name']=$t['name'];
$out[$i]['file']=$t['file'];
$out[$i]['age']=$t['age'];
$out[$i]['date_time']=$t['date_time'];
$i++;
}
return $out;
So that I can fetch the $out according to my necessary.
Can any one please help me ?
Thanks in advance
As you provided in the php code in your question, it's not a single column. It's a row data. So, which you basically want is the entire row information. In order to get the entire row details, you have to do something like this.
String name = cursor.getString(cursor.getColumnIndex("name"));
String address = cursor.getString(cursor.getColumnIndex("address"));
So, the generic would be:
datatype fetchedData = cursor.getterofthatparticulardatatype(cursor.getColumnIndex(columnName));
Edit:
Either use POJO class as the other answerer said or this:
public List<HashMap<String, String>> getMyDetails()
{
List<HashMap<String, String>> datalist = new ArrayList<HashMap<String, String>>();
Cursor cursor = myDataBase.rawQuery("SELECT * FROM pic_details WHERE _id=1",null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> hashmap = new HashMap<String, String>();
String name = cursor.getString(cursor.getColumnIndex("name"));
String story = cursor.getString(cursor.getColumnIndex("story"));
hashmap.put("nameKey",name);
hashmap.put("storyKey",story);
dataList.add(hashmap);
} while (cursor.moveToNext());
}
return dataList;
}
The way you should retrieve:
List<HashMap<String, String>> piclist= dbHelper. getMyDetails();
for(HashMap hashmap : piclist)
{
String name = hashmap.get("nameKey");
String story = hashmap.get("storyKey");
Log.d("name,story",name+", "+story);
}
First you create Java class.
public class Person {
private String image;
private String name;
public Person(String image, String name) {
super();
this.image = image;
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Then create ArrayList of person class
Public List<Person> getMyDetails()
{
List<Person> dataList = new ArrayList<Person>();
Cursor cursor = myDataBase.rawQuery("SELECT * FROM pic_details WHERE _id=1",null);
if (cursor .moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
person = new Person(image, name)
dataList.add(person);
} while (cursor.moveToNext());
}
return dataList;
}
Then use this arraylist in you activity class.

Android & SQLite : how to display the multiple column value

i hope you guys can help to solve my problem.
my problem is cant retrieve the multiple value of column. In my database contain 4 columns (id, namaStation, ticket, masa). right now the program only displayed value of namaStation. It mybe because of the toString() method in Comment class because its only return 1 value (namaStation). can help me??
This is my program. ##
1. Call the query.
`public void onClick(View view) {
#SuppressWarnings("unchecked")
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter();
Comment comment = null;
switch (view.getId()) {
case R.id.add:
List<Comment> values = datasource.query("Kelana Jaya");
adapter = new ArrayAdapter<Comment>(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
break;`
2. The query.
#SuppressWarnings("static-access")
public List<Comment> query(String namaStation){
//List<Comment> comments = new ArrayList<Comment>();
database = dbHelper.getReadableDatabase();
List<Comment> comments = new ArrayList<Comment>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
allColumns, MySQLiteHelper.COLUMN_namaStation+"=?",new String[]{namaStation}, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
// Comment comment = cursorToComment(cursor);
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setNamaStation(cursor.getString(1));
comments.add(comment);
comment.setTicket(cursor.getString(2));
comments.add(comment);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return comments;
3. The Comment class
public class Comment {
private long id;
public String namaStation;
public String ticket;
public String masa;
public String comment;
public int x;
public Comment(){
}
public Comment(long id, String namaStation, String ticket, String masa){
this.id=id;
this.namaStation=namaStation;
this.ticket=ticket;
this.masa=masa;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNamaStation() {
return namaStation;
}
public void setNamaStation(String comment) {
this.namaStation = comment;
}
public String getTicket() {
return ticket;
}
public void setTicket(String comment) {
this.ticket = comment;
}
public String getMasa() {
return masa;
}
public void setMasa(String comment) {
this.masa= comment;
}
// Will be used by the ArrayAdapter in the ListView
public String toString() {
return ticket;
}
}
The display (the layout is not in proper way because im not setup its yet.. :) )
the display
You should do your own ArrayAdapter. You could supply an own layout for your items.
So you could place any column where you want.
Just to join all fields in toString is not "high tech".
It may be sufficient in simple cases
May the following link is helpful
http://www.vogella.de/articles/AndroidListView/article.html#listview_adapterintro
You add the comment twice to the list
comments.add(comment);
comment.setTicket(cursor.getString(1));
comments.add(comment);
sidenote: you can simplify
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
// do stuff
cursor.moveToNext();
}
to this
while (cursor.moveToNext()) {
// do stuff
}
And the actual Problem that you see only the name is that you use the wrong Adapter. You need to create your own. Either based on ArrayAdapter if there is a reason to convert your query result into an array - or directly by using a CursorAdapter.
here is an example you can use.

Categories

Resources