Retrieve data from SQLite database - android

inHow do i retrieve data from sqlite database from adapter class and insert to listview???
I'm having difficulty, been coding day & night and googling non-stop but i just don't understand the links when i open them up. I just start learning android programming recently on my own...
I have attach my code below
public Cursor RetrieveActivityCursor(String NRIC){
String where = NRIC;
Cursor cursor = _db.query(DATABASE_TABLE,new String[]{ MOBILE_HOUSE_VISIT_ID, ELDERLY_NAME,
ELDERLY_NRIC, ELDERLY_DATE_TIME, PHYSICAL_HEALTH_STATUS, MENTAL_HEALTH_STATUS} , where, null, null, null, null);
//Cursor cursor = _db.query(DATABASE_TABLE, new String[] { ELDERLY_NAME,
//ELDERLY_NRIC, DATE_TIME, PHYSICAL_HEALTH_STATUS, MENTAL_HEALTH_STATUS }, null, null, null, null, null);
return cursor;
}
this code is from my adapter class and have to pass in nric and return datetime value inserted into listview
im not too sure how to code to call this method.

If you are extending the SqliteOpenHelper for the database handling and using another class to which extends Activity, in which you have your ListView then, in your Activity class make the object of your class like,
YourDBClass helperDB;
helperDB = new HelperDB(YourActivityClass.this);
And to retrive the data from the Database.
Make Cursor reference like,
Cursor cursor;
And then, do like this,
cursor = helperDB.RetrieveActivityCursor(NRIC);
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
// here you have to collect the data in the collection object.
cursor.moveToNext();
}
cursor.close();
That's it! And you have done with retriving data from database

you need iterate cursor, like this:
Cursor cursor = RetrieveActivityCursor(NRIC);
if (cursor != null && cursor.moveToNext())
do {
String str = cursor.getString(cursor.getColumnIndex("your_column"));
// do something, your code
} while (cursor.moveToNext());

Where you like to retrieve the date value do the below over there.
Cursor cursor = RetrieveActivityCursor(NRIC);
if(mCursor.moveToFirst()) {
do{
String date_time = cursor.getString(cursor.getColumnIndex(column_name));
} while(mCursor.moveToNext());
}
cursor.close();

Related

How to write a sqlite query to get specific data?

I want to get the first name, middle name and last name of a student whose userid is used for login. I have written this particular piece of code but it stops my application.
I have used both the ways like database.query() and .rawquery() also.
Cursor studentData(String userId) {
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query(studentTable, new String[] { "First_Name", "Middle_Name", "Last_Name"}, "User_ID=?", new String[] { userId }, null, null, null, null);
// Cursor cursor = db.rawQuery("select First_Name, Middle_Name, Last_Name from Student_Table where User_ID =?", new String[]{userId});
String data = cursor.getString(cursor.getColumnIndex("First_Name"));
db.close();
return cursor;
}
I should get whole name in the string.
You have a number of issues.
Attempting to use String data = cursor.getString(cursor.getColumnIndex("First_Name"));,
will result in an error because you have not moved the cursor beyond BEFORE THE FIRST ROW and the attempt to access the row -1 will result in an exception (the likely issue you have encountered).
you can use various move??? methods e.g. moveToFirst, moveToNext (the 2 most common), moveToLast, moveToPosition.
Most of the Cursor move??? methods return true if the move could be made, else false.
You CANNOT close the database and then access the Cursor (this would happen if the issue above was resolved)
The Cursor buffers rows and then ONLY when required.
That is The Cursor is when returned from the query method (or rawQuery) at a position of BEFORE THE FIRST ROW (-1), it's only when an attempt is made to move through the Cursor that the CursorWindow (the buffer) is filled (getCount() included) and the actual data obtained. So the database MUST be open.
If you want a single String, the full name, then you could use :-
String studentData(String userId) { //<<<<<<<<<< returns the string rather than the Cursor
SQLiteDatabase db = getWritableDatabase();
String rv = "NO NAME FOUND"; //<<<<<<<<<< value returned if no row is located
Cursor cursor = db.query(studentTable, new String[] { "First_Name", "Middle_Name", "Last_Name"}, "User_ID=?", new String[] { userId }, null, null, null, null);
if (cursor.modeToFirst()) {
String rv =
cursor.getString(cursor.getColumnIndex("First_Name")) +
" " +
cursor.getString(cursor.getColumnIndex("Middle_Name")) +
" " +
cursor.getString(cursor.getColumnIndex("Last_Name"));
}
cursor.close(); //<<<<<<<<<< should close all cursors when done with them
db.close(); //<<<<<<<<<< not required but would result in an exception if returning a Cursor
return rv;
}
Or alternately :-
String studentData(String userId) { //<<<<<<<<<< returns the string rather than the Cursor
SQLiteDatabase db = getWritableDatabase();
String rv = "NO NAME FOUND"; //<<<<<<<<<< value returned if no row is located
Cursor cursor = db.query(studentTable, new String[] { "First_Name"||" "||"Middle_Name"||" "||"Last_Name" AS fullname}, "User_ID=?", new String[] { userId }, null, null, null, null);
if (cursor.modeToFirst()) {
String rv =
cursor.getString(cursor.getColumnIndex("fullname"));
}
cursor.close(); //<<<<<<<<<< should close all cursors when done with them
db.close(); //<<<<<<<<<< not required but would result in an exception if returning a Cursor
return rv;
}
the underlying query being SELECT First_Name||" "||Middle_Name||" "||LastName AS fullname FROM student_table; so you concatenate the names as part of the query which returns just one dynamically created column named fullname.

Filling the list

In the below code I get data from database and add them to the court class, finally add the court class to the courtList.
But the final courtList's items are the same . All the data are the last data in the database.
How can I solve it? Where is my mistake?
Thank's
public List<Court> getListOfCourt(){
List<Court> courtList;
Court court= new Court();
String[] col= new String[]{
CourtTable.OFFICE_FILE_CODE,
CourtTable.CLIENT_ID,
CourtTable.COURT_DATE
};
SQLiteDatabase sd= getReadableDatabase();
Cursor cur= sd.query(CourtTable.TABLE_NAME, col, null, null, null, null,null);
courtList = new ArrayList<Court>() ;
if(cur!=null && cur.getCount()>0){
cur.moveToFirst();
do{
court.setOfficeFileCode(cur.getInt(cur.getColumnIndex(CourtTable.OFFICE_FILE_CODE)));
court.setClientId(cur.getInt(cur.getColumnIndex(CourtTable.CLIENT_ID)));
court.setCourtDate(cur.getString(cur.getColumnIndex(CourtTable.COURT_DATE)));
courtList.add(court);
}
while(cur.moveToNext());
}
return courtList;
}
Put this line " Court court= new Court(); " inside do block as first statement.

How do you iterate over a cursor in reverse order

Usually when I iterate over a cursor I use something like the following:
while (cursor.moveToNext()) {
// get stuff from the cursor
}
What's the best way to iterate an Android Cursor? has a nice discussion of the various options. But now I need to go backwards from last to first over the cursor.
So what can I do?
There are at least two options.
First, to specifically answer your question about iterating backwards over the cursor, you could do the following:
for (cursor.moveToLast(); !cursor.isBeforeFirst(); cursor.moveToPrevious()) {
// get stuff from the cursor
}
Second, you could populate the cursor in reverse order from sql and then iterate over the cursor in your normal way:
SQLiteDatabase db = myHelper.getWritableDatabase();
String[] columns = { MyDatabaseHelper.TEST_DATE, MyDatabaseHelper.SCORE };
String orderBy = MyDatabaseHelper.TEST_DATE + " DESC"; // This line reverses the order
Cursor cursor = db.query(MyDatabaseHelper.TESTS_TABLE_NAME, columns,
null, null, null, null, orderBy, null);
while (cursor.moveToNext()) {
// get stuff from the cursor
}
cursor.close();
db.close();
You can start the cursor in the last position, and use moveToPrevious() until you've finished.
cursor.moveToLast();
do
{
// Stuff
}
while (cursor.moveToPrevious());

How to store a row from a cursor

I want to pull a row from a data-filled cursor and store it in another object for other use.
my code:
SQLiteDatabase db = dbOpener.getReadableDatabase();
Cursor dataSet = db.query(WPTemplateDB.PRODUCT_TABLE,
null, //all columns
null, //where clause
null, //where clause args
null, null, null);//groupBy, having, orderBy
while (dataSet.moveToNext()){
Product product = new Product(dataSet);
pArray.add(product);
}
my storing object:
public Product(Cursor cursor){
productData = cursor;
}
public String getData(String column){
Log.d(column, productData.getColumnIndex(column)+"");
return productData.getString(productData.getColumnIndex(column));
}
Now, I am facing an error of "index 10 requested with a size of 10". What can I do to this?
Don't should using cursor is contructors for Product objects. It will leak memory because cursor must close when not use.
You should read data from cursor then send data to contructor Product like:
String productName = cursor.getString(0);// 0 is column name
......
cursor.close();
Product product = new Product(name);
Indexes are zero-based. It means that is size is 10, max index will be 9. From the code you've posted, everything is fine, so the error in some other place of your code.
Actually, this answer is inspired from #cuasodayleo, I just translate it to be another code.
SQLiteDatabase db = dbOpener.getReadableDatabase();
Cursor dataSet = db.query(WPTemplateDB.PRODUCT_TABLE,
new String[]{WPTemplateDB.PRODUCT_ID},
null, //where clause
null, //where clause args
null, null, null);//groupBy, having, orderBy
while (dataSet.moveToNext()){
Product product = new Product(dataSet.getInt(0), db);
pArray.add(product);
}
dataSet.close();
The Product object:
public Product(int pid, SQLiteDatabase db){
productData = db.query(WPTemplateDB.PRODUCT_TABLE,
null, //all columns
WPTemplateDB.PRODUCT_ID+"=?", //where clause
new String[]{pid+""}, //where clause args
null, null, null);//groupBy, having, orderBy
}
public String getData(String column){
Log.d("count", productData.getCount()+"");
if (productData.getCount()>0){
Log.d(column, productData.getColumnIndex(column)+"");
productData.moveToFirst();
return productData.getString(productData.getColumnIndex(column));
} else {
return null;
}
}

Android SQLite rawquery returns only first record

My SQLite query returning only one record, However, the table has multiple rows
cursor=mydb.rawQuery("Select category from items;", null);
I have even tried GROUP BY but still wont work.
I am new to SQLite, would appreciate any help. Thanks.
First of all your string query must not be terminated so instead of passing it as:
"Select category from items;"
you should try passing it as:
"Select category from items"
as mentioned on this page.
Also, are you looping over the cursor? Here is an example of how to get data out of a cursor with a while loop:
ArrayList<String> results = new ArrayList<String>()
while (cursor.moveNext()) {
results.add(cursor.getString(0)); // 0 is the first column
}
First, search:
Cursor cs = myDataBase.rawQuery("Your query", null);
if (cs.moveToFirst()) {
String a = cs.getString(cs.getColumnIndex("your_column_name"));
cs.close();
return a;
}
cs.close();
return "";
Get the information from cursor:
if (cs.moveToFirst()) {
ArrayList<String> results = new ArrayList<String>()
do {
results.add(cs.getString(cs.getColumnIndex("your_column_name")));
} while (cs.moveNext());
}
Without if, I took error in my project. But this worked for me. By the way, your query doesn't look good. If you give some information about your database, we can help much more.
Use this to select all items from the table:
Cursor cursor = db.rawQuery("SELECT * FROM Tablename ,
null);
this can help you
public ArrayList<mydata> getallContents() {
ArrayList<mydata> lst = new ArrayList<mydata>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("select * from " + GAMETABLE, null);
if (c.moveToFirst()) {
do {
lst.add(new mydata(c.getString(1),
c.getString(3),c.getString(4),c.getString(5),c.getString(6)));
} while (c.moveToNext());
}
db.close();
return lst;
}
you don't need raw query method. i think that the android way is better in this case:
db.query(items, category, null, null, null, null, null);
than use the cursor how already is written in the other comment.

Categories

Resources