android sqlite items - android

hi to all i have this android sqlite code to read all the titles from a table and this code is in the DBHelper.java
//---retrieves all the titles---
public Cursor getAllTitles()
{
return db.query(DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_BOOK,
KEY_AUTHOR,
KEY_EDITION,
KEY_YEAR,
KEY_RETURNDATE},
null,
null,
null,
null,
null);
and this is the code in my main app.....
//---get all titles---
db.open();
Cursor c = db.getAllTitles();
if (c.moveToFirst())
{
do {
DisplayTitle(c);
} while (c.moveToNext());
}
my question is that i want to get for example the returendate so i can compare it to the current time and based on that i will make an action
so can i read it ....buffer[5] and compare it....???

Assuming your return date is a string, you can use the following in your DisplayTitle(cursor c) :
String returnDate = c.getString(c.getColumnIndex(KEY_RETURNDATE));

public void doWork()
{
db.open();
Cursor c = db.getAllTitles();
if(c==null)
return;
for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
{
String key= c.getString(c.getColumnIndex(c.getColumnName(5)));
//and now you can put the condition to compare current time with key
}
}

Use c.getString(c.getColumnIndex(KEY_RETURNDATE));as rajath said, and don't forget to close your Cursor after your loop if you don't need it any more: c.close(); else you will have a memory leak.

Related

android-how to close cursor in a class like this

I have this function inside my dbhelper class :
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(DATABASE_TABLE, ALL_KEYS, where, null, null, null,null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
when I come to the activity where this class calls, I get this error (Please notice when I enter this activity I get this error not when leaving the activity ):
Finalizing a Cursor that has not been deactivated or closed. database......
Application did not close the cursor or database object that was opened here
it's a very long error .
someone told me to use c.close(); above return c, something like this:
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(DATABASE_TABLE, ALL_KEYS, where, null, null, null,null, null);
if (c != null) {
c.moveToFirst();
}
c.close();
return c;
}
I tried it but now I get this error :
Access closed cursor
What should I do ? How should I close the cursor in this class?
You should close the Cursor in your Activity. like
Cursor c=getRow(rowID_Value);
c.close();
After getting used of your DB you must close this Cursor.
Close the cursor after using getRow function,i.e.
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(DATABASE_TABLE, ALL_KEYS, where, null, null, null,null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
and use it like this
Cursor c1 = getRow(rowId);
//use cursor
//....
if(c1 != null)c1.close();
Note : rowId is the value of row which you want from database in long format.
Edit
Create Cursor c1; in your activity class.
check first if cursor is not null,then close it.
if(c1 != null)c1.close();
then get cursor as
c1 = getRow(rowId);
And onStop/onDestroy close cursor as
if(c1 != null)c1.close();
hello i have face this same problem i have solve this problem like
when i am query and returning ArrayList or JSON object not cursor
may you need to change your query
public JSONObject getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(DATABASE_TABLE, ALL_KEYS, where, null, null, null,null, null);
if (c!= null & c.moveToFirst()) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("key_Name", c.getString(c.getColumnIndex("your_column_name")));
// do for your all column and return this jsonObj and before returning close cursor
}
c.close();
return jsonObj;
}
this is for only returning one record for retuning set of record i am use this lib
https://github.com/commonsguy/cwac-loaderex
it will manage cursor operation itself and return us sqliteCursorLoader

exception: cursor index out of range

Here is the code in activity:
//query
final dbhelper helper = new dbhelper(this);
Cursor c = helper.query();
boolean exist =false;
if(c != null && c.moveToFirst()){
Log.d("atestdbChar1no",String.valueOf(c.getCount()));
int i=0;
while(c.isAfterLast()){
Log.d("atestdb1",String.valueOf(i++));
Log.d("atestdb2",String.valueOf(c.getInt(0)));
Log.d("atestdb3",c.getString(1));
Log.d("atestdb4",c.getString(2));
c.moveToNext();
}
//insert
ContentValues values = new ContentValues();
if(!finWords.equals("null")){
if(finWords.length()>index){
String selectWord = finWords.substring(index, index+1);
values.put("character", finChar);
values.put("word", selectWord);
helper.insert(values);
Here is the code in SQLiteOpenHelper:
public void insert(ContentValues values) {
SQLiteDatabase db = getWritableDatabase();
db.insert(TBL_NAME, null, values);
Log.d("test", "dbinsert");
db.close();
}
public Cursor query() {
SQLiteDatabase db = getWritableDatabase();
Cursor c = db.query(TBL_NAME, null, null, null, null, null, null);
Log.d("test", "dbquery");
return c;
}
I can insert data into database
but I cannot query them
the logcat say the cursor index out of range
and just output some data for example just output with id 1,2,4,7 then force close the App
but I already insert 14 data
what wrong of my code?
You forgot to negate c.isAfterlast() and unless you pass null back you do not have to check for null cursor.
if(c.moveToFirst()){
Log.d("atestdbChar1no",String.valueOf(c.getCount()));
int i=0;
while(!c.isAfterLast()){
Log.d("atestdb1",String.valueOf(i++));
Log.d("atestdb2",String.valueOf(c.getInt(0)));
Log.d("atestdb3",c.getString(1));
Log.d("atestdb4",c.getString(2));
c.moveToNext();
}

How to retrieve a record from sqlite

Hi i'm new to android programming and i have created a sample app which allows the user to get data from the database. however its not displaying the data, it doesn't have any error message its just not displaying it. database is confirmed that there is data. please check my code maybe i forgot something here. thanks
public void onClick(View arg){
name = txtNameS.getText().toString();
if(arg.getId()==R.id.btnfortune){
searchRecord(count);
lblmessageS1.setText(name); // this is just for me to check if it will be displayed and it is.
lblmessageS2.setText(message);
}
}
public void searchRecord(int count) throws SQLException {
Cursor rsCursor;
String [] rsFields = {"mesNum","Message"};
rsCursor = dbM.dbase.query("MessageFile", rsFields, "mesNum = " + count, null, null, null, null, null);
rsCursor.moveToFirst();
if (rsCursor.isAfterLast()==false){
message = rsCursor.getString(1);
}
rsCursor.close();
}
by the way count is initialized as 1. and there are 10 records in the database. and there are 2 columns in the database the mesNum and Message, what i want is to display only the message column.
// SQLiteDatabase sqldb
Cursor rsCursor= sqldb.rawQuery("your query", null);
if (rsCursor!= null) {
if (rsCursor.moveToFirst()) {
do {
// do here for get data message = rsCursor.getString(1);
}while (cursor.moveToNext());
}
cursor.close();
}
add only one column name in your array
String [] rsFields = {"Message"};
cursor = dbM.dbase.query(true,"MessageFile", rsFields, "yourcolumn= "+count, null, null, null, null, null);
while( cursor != null && cursor.moveToNext() )
{
cursor.getString(0);
}
cursor.close();

Get all rows from SQLite

I have been trying to get all rows from the SQLite database. But I got only last row from the following codes.
FileChooser class:
public ArrayList<String> readFileFromSQLite() {
fileName = new ArrayList<String>();
fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
fileSQLiteAdapter.openToRead();
cursor = fileSQLiteAdapter.queueAll();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
fileName.add(cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1)));
} while (cursor.moveToNext());
}
cursor.close();
}
fileSQLiteAdapter.close();
return fileName;
}
FileSQLiteAdapter class:
public Cursor queueAll() {
String[] columns = new String[] { KEY_ID, KEY_CONTENT1 };
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns, null,
null, null, null, null);
return cursor;
}
Please tell me where is my incorrect. Appreciate.
try:
Cursor cursor = db.rawQuery("select * from table",null);
AND for List<String>:
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
Using Android's built in method
If you want every column and every row, then just pass in null for the SQLiteDatabase column and selection parameters.
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null, null);
More details
The other answers use rawQuery, but you can use Android's built in SQLiteDatabase. The documentation for query says that you can just pass in null to the selection parameter to get all the rows.
selection Passing null will return all rows for the given table.
And while you can also pass in null for the column parameter to get all of the columns (as in the one-liner above), it is better to only return the columns that you need. The documentation says
columns Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
Example
SQLiteDatabase db = mHelper.getReadableDatabase();
String[] columns = {
MyDatabaseHelper.COLUMN_1,
MyDatabaseHelper.COLUMN_2,
MyDatabaseHelper.COLUMN_3};
String selection = null; // this will select all rows
Cursor cursor = db.query(MyDatabaseHelper.MY_TABLE, columns, selection,
null, null, null, null, null);
This is almost the same solution as the others, but I thought it might be good to look at different ways of achieving the same result and explain a little bit:
Probably you have the table name String variable initialized at the time you called the DBHandler so it would be something like;
private static final String MYDATABASE_TABLE = "anyTableName";
Then, wherever you are trying to retrieve all table rows;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + MYDATABASE_TABLE, null);
List<String> fileName = new ArrayList<>();
if (cursor.moveToFirst()){
fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
while(cursor.moveToNext()){
fileName.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
}
}
cursor.close();
db.close();
Honestly, there are many ways about doing this,
I have been looking into the same problem! I think your problem is related to where you identify the variable that you use to populate the ArrayList that you return. If you define it inside the loop, then it will always reference the last row in the table in the database. In order to avoid this, you have to identify it outside the loop:
String name;
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
name = cursor.getString(cursor
.getColumnIndex(countyname));
list.add(name);
cursor.moveToNext();
}
}
Update queueAll() method as below:
public Cursor queueAll() {
String selectQuery = "SELECT * FROM " + MYDATABASE_TABLE;
Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);
return cursor;
}
Update readFileFromSQLite() method as below:
public ArrayList<String> readFileFromSQLite() {
fileName = new ArrayList<String>();
fileSQLiteAdapter = new FileSQLiteAdapter(FileChooser.this);
fileSQLiteAdapter.openToRead();
cursor = fileSQLiteAdapter.queueAll();
if (cursor != null) {
if (cursor.moveToFirst()) {
do
{
String name = cursor.getString(cursor.getColumnIndex(FileSQLiteAdapter.KEY_CONTENT1));
fileName.add(name);
} while (cursor.moveToNext());
}
cursor.close();
}
fileSQLiteAdapter.close();
return fileName;
}
Cursor cursor = myDb.viewData();
if (cursor.moveToFirst()){
do {
String itemname=cursor.getString(cursor.getColumnIndex(myDb.col_2));
String price=cursor.getString(cursor.getColumnIndex(myDb.col_3));
String quantity=cursor.getString(cursor.getColumnIndex(myDb.col_4));
String table_no=cursor.getString(cursor.getColumnIndex(myDb.col_5));
}while (cursor.moveToNext());
}
cursor.requery();
public List<String> getAllData(String email)
{
db = this.getReadableDatabase();
String[] projection={email};
List<String> list=new ArrayList<>();
Cursor cursor = db.query(TABLE_USER, //Table to query
null, //columns to return
"user_email=?", //columns for the WHERE clause
projection, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null);
// cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(cursor.getColumnIndex("user_id")));
list.add(cursor.getString(cursor.getColumnIndex("user_name")));
list.add(cursor.getString(cursor.getColumnIndex("user_email")));
list.add(cursor.getString(cursor.getColumnIndex("user_password")));
// cursor.moveToNext();
} while (cursor.moveToNext());
}
return list;
}
a concise solution can be used for accessing the cursor rows.
while(cursor.isAfterLast)
{
cursor.getString(0)
cursor.getString(1)
}
These records can be manipulated with a loop

getting row id of a database

what i want to do is do a search of my database for a string then find out what the row id is where that string is.
I thought by doing this
public void getRow(){
ContactDB db = new ContactDB(this);
db.open();
Cursor c = db.getId("1234567890");
String test = c.getString(c.getColumnIndex(db.PHONE_NUMBER));
Log.v("Contact", "Row ID: " + test);
db.close();
database class
public Cursor getId(String where){
return db.query(DATABASE_TABLE, new String[] {ID},where,null,null,null,null);
}
that it would give me what i want but i get a "cursor index out of bounds" error, how should i be doing this?
change getId to:
public Cursor getId(String where){
Cursor c = db.query(DATABASE_TABLE, new String[] {ID},where,null,null,null,null);
if (c != null) c.moveToFirst();
return c;
}
You need to do c.moveToFirst() before tying to read any information.
Also do c.close() when you're done.

Categories

Resources