Can't get any values in the cursor - android

I'm confused why I can't get any values in the cursor.
What's wrong in my code..
here's the code..
sqLiteDatabase = getReadableDatabase();
Cursor cursor = sqLiteDatabase.query("bank",new String[]{"name", "acno", "available"},"bank_index = ?",new String[]{String.valueOf(bank_index)},null,null,null);
cursor.moveToFirst();
String name = cursor.getString(cursor.getColumnIndex("name"));
String acno = cursor.getString(cursor.getColumnIndex("acno"));
contentValues.put("bank", name + " Account number: " + acno);
I got error of CursorOutOfBoundsException on last third line of the above code..
query of the table:
sqLiteDatabase.execSQL("create table bank(bank_index integer primary key,name text,acno text,branch text,available text)");

Before performing any operation on cursor, you must check
if(cursor != null && cursor.getCount() > 0 ) {
//go ahead
}
//You can also try
String query = "SELECT name, acno, available FROM bank WHERE bank_index = '"+String.valueOf(bank_index)+"'";
Cursor cursor = sqLiteDatabase.rawQuery(query,null);

Related

How to get last record from table SQLite

I have problem with receiving last data from table in Android SQLite.
Adding values works great but I struggle with receiving last date from table, here is code:
int getKoniec() {
SQLiteDatabase db = this.getReadableDatabase();
String sortOrder = TABELA_koniec + " DESC LIMIT 1";
Cursor cursor = db.query(
TABELA,
new String[] { "koniec" },
null,
null,
null,
null,
sortOrder
);
if(cursor != null) {
cursor.moveToFirst();
}
int koniecINT = cursor.getInt(0);
Log.v("VALUE: ","" + koniecINT);
cursor.close();
return koniecINT;
}
While adding values 10,9,8,7.. output (return koniecINT) is always 10.
Can you help me to solve this problem? Thanks
Try this query
select * from table_name order by row_id desc limit 1
or
mCursor.moveToLast();

How to delete specific data from a particular column in SQLite?

My app has a sqlite table which has the following columns:
CONTACT_ID = "_id",
CONTACT_NAME = "con_name",
CONTACT_USERID = "con_userid",
CONTACT_ACCID = "con_accid".
The content of the column con_accid is of type String. The primary key of the table is id. I want to delete data of particular con_accid. For example, I want to delete item names of all items which have con_accid as "raja". I have tried the following different queries but both are not working:
Cursor cursor = database.query(ContactsDB.TABLE_CONTACTS, allColumns,
ContactsDB.CONTACT_ACCID + "= ' " + comment +"'" , null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Log.i(TAG, "delete");
ContactsInfo _comment = cursorToComment(cursor);
long id = _comment.getId();
database.delete(ContactsDB.TABLE_CONTACTS, ContactsDB.CONTACT_ID + "=" + id , null);
cursor.moveToNext();
}
}
and this:
String query = "SELECT * FROM todo WHERE con_accid='" + comment;
Cursor cursor = database.rawQuery(query,null);
This should delete all rows in your database where con_accid = raja:
database.delete(TABLE_CONTACTS, CONTACT_ACCID + " = ?", new String[] {"raja"});
Check "database" instance is created with .getWritableDatabase(). And your query should work without any issue.

select one cell from sql database

I'm trying a simple SQL Command wihtin my Android-App, to get the age of a selected Person:
public int getAge(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name =? " + MainActivity.selectedPerson.getText().toString(), null);
int age = cursor.getInt(3); // column with ages
cursor.close();
db.close();
return age;
}
But when I run my app, it crashes when I call the function getAge(). I get the following Error:
SQLiteException: no such column: Max: , while compiling: SELECT * FROM persons WHERE name = Max
I don't get it. There is the name "Max" in the table. What am I doing wrong? Thanks in advance.
Edit 2:
With this one:
Cursor cursor = db.rawQuery("SELECT name FROM persons WHERE name = '" + MainActivity.selectedPerson.getText().toString() + "'", null);
I get a different error:
08-27 19:43:47.573: E/AndroidRuntime(6161): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
what does this mean?
You should consider using the selectionArgs parameter of rawQuery() to prevent SQL Injection Attacks:
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name = ?", new String[] { MainActivity.selectedPerson.getText().toString() });
Also you only need one column so rather than wasting resources by selecting them all with *, you should just select the one column:
Cursor cursor = db.rawQuery("SELECT age FROM persons WHERE name = ?", new String[] { MainActivity.selectedPerson.getText().toString() });
Hope that helps!
All together it should look like:
public int getAge(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT age FROM persons WHERE name = ?", new String[] { MainActivity.selectedPerson.getText().toString() });
int age;
// Check if you have a valid result and move to the first row to read it
if(cursor.moveToFirst())
age = cursor.getInt(0);
// Prevent a crash if there is no data for this name
else
age = 0;
cursor.close();
db.close();
return age;
}
Chan ge the 3rd line of your program:
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name =? " + MainActivity.selectedPerson.getText().toString(), null);
to this:
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name = ?", new String[] { MainActivity.selectedPerson.getText().toString()} );
Try this:
public int getAge(){
int age;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name = '" + MainActivity.selectedPerson.getText().toString()+"'",null);
if(cursor.moveToFirst())
{
age = cursor.getInt(3); // column with ages
}
cursor.close();
db.close();
return age;
}
You missed the single quotes (' ') in your sql command. That's why MAX was taken as a column and not as a value.

How to get all the primary key Values using Cursor and add it in Arraylist?

CREATE TABLE IF NOT EXISTS tableName _id integer primary key autoincrement,Title varchar ,Description varchar .
My table name look like this.
Please anyone help me on this.
I'd suggest explaining the question a little further, but I believe what you're looking for is a way to iterate through a cursor and get all of the primary keys. Try something like this:
ArrayList<Long> ids = new ArrayList<Long>();
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
do {
long id = cursor.getLong(cursor.getColumnIndex(KEY_ROWID));
ids.add(id);
} while (cursor.moveToNext());
}
Let's try the below code,
If suppose the table have two columns as _id and name,while querying the Select statement we know the columnindex of resulting query.
ArrayList<Integer> keyid = new ArrayList<Integer>();
ArrayList<String> names= new ArrayList<String>();
int id= 0;
String name = null
String statement = "Select * from " + TABLE_NAME;
Cursor c = db.rawQuery(statement, null);
if (c.moveToFirst()) {
do {
id = c.getInt(0);
name= c.getString(1);
keyid.add(id);
names.add(name);
} while (c.moveToNext());
}
c.close();

row id from database

i am trying to do a query of my database for a string lets call it "Test" and then find out what row that particular string is in and save that number to use. I thought i had this figured out before but now it is not working for some reason and i get an error saying no such column "Test".
here is my code
public String getRow(String value){
ContactDB db = new ContactDB(this);
db.open();
Cursor curs = db.getId(value);
String test = curs.getString(curs.getColumnIndex(db.NAME));
curs.close();
Log.v("Contact", "Row ID: " + test);
db.close();
return test;
}
"Test" is sent into that as value
this is in my database
//---retrieve contact id---
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;
}
i dont remember changing anything from when i first tested it so i dont know why it wont work now
There are 2 errors that i could notice:
In the query
Cursor c = db.query(DATABASE_TABLE, new String[] {ID},where,null,null,null,null);
only the ID column is selected whereas you are trying to fetch details for column NAME
String test = curs.getString(curs.getColumnIndex(db.NAME));
include the name column as well in the select clause : something like
Cursor c = db.query(DATABASE_TABLE, new String[] {ID,NAME},where,null,null,null,null);
In the where clause you need to write the condition string excluding "where"
in your case String where contains value "Test". Hence the filter condition should be as
String whereClasue = NAME + " = '" + where + "'";
The query should be something like this:
public Cursor getId(String where){
Cursor c = db.query(DATABASE_TABLE, new String[] {ID,PHONE_NUMBER,NAME},NAME + " = '" + where + "'",null,null,null,null);
if (c != null)
c.moveToFirst();
return c;
}

Categories

Resources