is there any thing wrong with this code, i want to query for data by using barcode and it show me that Cursor Index out of Bound exception .
public String getIdByBarcode(String ss) throws SQLException{
String[] column = new String[]{Pro_ID,Pro_Barcode, Pro_Name,Pro_NameKhmer, Pro_Quantity, Pro_Price, Pro_Description, Pro_Date};
Cursor c = ourDatabase.query(TABLE_NAME, column, Pro_Barcode + "= '" + ss + "' " , null, null, null, null);
if(c != null){
c.moveToFirst();
String id = c.getString(0);
Log.v(id, id + "Id" );
return id;
}
return null;
}
No results in the Cursor. You should check what moveToFirst() is returning (most likely false). Also you should use moveToNext(), not moveToFirst(). Also watch out that you're not checking ss parameter. This could lead to SQL injection vulnerabilities. You should be using parameters. Also I think you can use a single return in your method.
public String getIdByBarcode(String ss) throws SQLException {
String[] column = new String[]{Pro_ID,Pro_Barcode, Pro_Name,Pro_NameKhmer, Pro_Quantity, Pro_Price, Pro_Description, Pro_Date};
final String args = new String[1];
args[0] = ss;
Cursor c = ourDatabase.query(TABLE_NAME, column, Pro_Barcode + " = ?" , args, null, null, null);
String ret = null;
if(c.moveToNext()) {
ret = c.getString(0);
}
return ret;
}
The literature of moveToFirst() method:
public abstract boolean moveToFirst () Move the cursor to the first row. This method will return false if the cursor is empty.
Returns whether the move succeeded.
So your moveToFirst call is failing(because cusrsor has 0 elements) and that is the reason for crash.
Do this:
if(c != null && c.moveToFirst()) {
String id = c.getString(0);
Log.v(id, id + "Id" );
return id;
}
try this
String id;
if (c!= null && c.moveToNext){
String id = c.getString(0);
return id;
}
Related
In my sql.query, there are times when the cursoe should return a null value. For example in the below code, the cursor is seeking a username. If the User has a username, then the cursor will return it. If not then I assume it is null. My problem is that when a cursor does find a null value, then I get a crash with an "out of bounds" error. Basically means the cursor did not find anything.
public static String getUserName() {
int rowIncrement = 1;
Log.d(DATABASE, "Getting Username");
String[] usercolumns = new String[] { KEY_ROWID, KEY_NAME, KEY_PASSWORD };
Cursor c = myDatabase.query(USER_TABLE, usercolumns, KEY_ROWID + "="
+ rowIncrement, null, null, null, null);
if (c != null) {
c.moveToFirst();
String lUserName = c.getString(1);
Log.d("DATABASE", "Username = " + lUserName);
return lUserName;
}
return null;
}
What is wrong with this code that would cause a crash if the cursor does not find anything?
It seems because of c.moveToFirst() returns boolean. So you should change your code like this.
if (c != null && c.moveToFirst()) {
String lUserName = c.getString(1);
Log.d("DATABASE", "Username = " + lUserName);
return lUserName;
}
You can check this here http://developer.android.com/reference/android/database/Cursor.html
I've spent some hours on trying to solve this but the only answer I get is that I can't select from a string? Is that so? How do I do it otherwise? Here's my code:
public String getHotness(String l) {
// TODO Auto-generated method stub
String[] columns = new String []{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
int iHotness = c.getColumnIndex(KEY_HOTNESS);
if (c != null){
c.moveToFirst();
String hotness = c.getString(iHotness);
return hotness;
}
return null;
}
Where l is a name of a person in my database. How would I select and get information from this person by his name?
Thanks! You guys are the best!
You can select only records that fit a specific criteria using the WHERE clause for the select. In case of SQLiteDatabase#query() method, you need to use the third parameter.
Other considerations:
You should use parameters instead of concatenating the values to avoid common issues (like SQL injections).
No need to check if returned Cursor is null, it never is (as the documentation also states).
Also you should close your Cursor before returning from the method.
Example:
final String theName = "The person name";
Cursor c = null;
try {
c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + " = ?", new String[]{theName}, null, null, null);
if (c.moveToNext()) {
// Do your stuff
}
} finally {
if (c != null) {
c.close();
}
}`
Note that previous query will only match rows where KEY_NAME column is exactly theName value. If you want to search by names that include theName value, you need to use LIKE operator instead.
final String likeName = "%" + theName + "%";
final Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + " LIKE ?", new String[]{likeName}, null, null, null);
LIKE is what you are looking for. % means anything BEFORE yourname is matching. ?yourname means only 1 char before. if you make sure that the name matches exactly you will need to use name = 'yourname' instead.
Cursor c = null;
try {
c = ourDatabase.rawQuery("SELECT * from yourtable where name LIKE '%yourname%', null);
if (c != null && c.getCount() > 0 && c.moveToFirst()) {
do {
c.getString(....);
} while (c.moveToNext());
}
} catch (Exception e) { e.printStackTrace(); }
finally {
if (c != null) c.close();
}
I'm running an update query that compiles. But when I test the results, there seem to be no changes. Everything looks good to me, but clearly something is wrong. Can anyone see what I am missing. Pretty new to SQLite, so apologies if it's something simple. Thanks!
public static Boolean updateHealth (int unitVal, int oldValue, int newValue) {
String unit = Integer.toString(unitVal);
String oldVal = Integer.toString(oldValue);
String newVal = Integer.toString(newValue);
System.err.printf("old val: %s, new val: %s\n", oldVal, newVal);
SQLiteDatabase db = myDBOpenHelper.getWritableDatabase();
String where = UNIT_COLUMN + " = " + unit + " AND " + HEALTH_COLUMN + " = " + oldVal;
Cursor cursor = db.query(UNITS_TABLE, new String[] {UNIT_COLUMN}, where, null, null, null, null);
if (cursor != null) {
/* the record doesn't exist, cancel the operation */
return false;
}
ContentValues updatedValues = new ContentValues();
updatedValues.put(HEALTH_COLUMN, newVal);
/* SQL query clauses */
String whereArgs[] = null;
db.update(UNITS_TABLE, updatedValues, where, whereArgs);
return true;
}
The cursor is not null when no row is retrieved. So you have to replace the line if (cursor != null) { by if(!cursor.moveToNext()) {
By the way, you don't need to query the database before updating. You can do the update, see how many rows have been affected and return true if the number of affected rows is > 0, false otherwise. The number of affected rows is returned by the method update.
I am trying to get the first column like below sql but my code show error.
SELECT subject FROM setting WHERE rowid=1
public void getSetting(){
result = "";
SQLiteDatabase db = myDbHelper.getReadableDatabase();
Cursor c = db.query(true, "setting", new String[] {"subject", "language", "selection"}, "row=1", null, null, null, null, null);
for(c.moveToFirst();!(c.isAfterLast());c.moveToNext()){
result = result + c.getString(0);
result = result + c.getString(0);
result = result + c.getString(0);
}
if (c.getCount() == 0)
result = result + "result not found";
c.close();
db.close();
myDbHelper.close();
}
Your stuff is a little hard to understand, but i think i have an idea what you want. You what to get a cursor to return only one row where the row's id is a specific value. And you only want the string from one column of that returned row. I assume that the primary issue is your designation of the _id column that you're looking for. You either called it row or rowid, you gotta double-check that.
Moreover, i hope the following re-write clears up further issues that you might have.
public String getSetting() {
String result = "";
String[] columns = {"subject"};
String[] selectionArgs = {"1"};
String LIMIT = String.valueOf(1); // <-- number of results we want/expect
SQLiteDatabase db = myDbHelper.getReadableDatabase();
Cursor c = db.query(true, "setting", columns, "rowid = ?", selectionArgs, null, null, null, LIMIT);
if (c.moveToFirst()) {
result = result + c.getString(0);
} else {
result = result + "result not found";
}
c.close();
myDbHelper.close();
return result;
}
Moreover, moreover. If you get an error you should post it so that we have an idea what's going on.
I am getting cursor index out of bounds "index 0 requested: with size 0" error when I search my database for something. The item I am searching for in my database does not exist currently and i am aware of that but how do i handle a query where the item does not exist.
i send in a phone number
public String searchNumber(Context context,String number){
ContactDB db = new ContactDB(context);
db.open();
Cursor curs = db.getIdFromPhone(number);
String test = curs.getString(curs.getColumnIndex(db.PHONE_NUMBER)); //fails here
curs.close();
db.close();
return test;
}
query
public Cursor getIdFromPhone(String where){
Cursor cur = db.query(DATABASE_TABLE, new String [] {ID,PHONE_NUMBER}
, PHONE_NUMBER + "='" + where + "'",null,null,null,null);
if(cur != null)
cur.moveToFirst();
return cur;
}
test search
from = messages.getDisplayOriginatingAddress();
String dbNumber = searchNumber(arg0,from);
if(dbNumber.equals(from)){
//do stuff
}else{
//do other stuff
}
if number is not found it should do the else statement but it does not get that far
Cursor.moveToFirst() returns false if the Cursor is empty. The returned Cursor from the query() call will never be null but it might be empty. You are never checking if the cursor is empty.
public String searchNumber(Context context,String number){
ContactDB db = new ContactDB(context);
db.open();
Cursor curs = db.query(DATABASE_TABLE, new String [] {ID,PHONE_NUMBER}
, PHONE_NUMBER + "='" + number + "'",null,null,null,null);
String test = null;
if(curs.moveToFirst()) { //edit
test = curs.getString(curs.getColumnIndex(db.PHONE_NUMBER)); //fails here
}
curs.close();
db.close();
return test; // this will be null if the cursor is empty
}
And get rid of the getIdFromPhone() method.
While you retrive value you have to use cursor.moveToNext;
if (cursor.moveToFirst()){
do{
String data = cursor.getString(cursor.getColumnIndex("data"));
// do what ever you want here
}while(cursor.moveToNext());
}