How do I select a specific string from an SQL database? - android

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();
}

Related

search sqlite with multiple columns

Hi every one I'm trying to search my sqlite data base which has 4 columns but the app crashes and the log error is :-
Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
I'm wondering if there is a method to search sqlite data base with multiple columns and with single columns.
The code for the cursor is :-
cursor = mReadableDB.query(WORD_LIST_TABLE, columns, where, whereArgs, null, null, null);
DataBase Code is :
public Cursor search(String searchString) {
String[] columns = new String[]{KEY_WORD};
String where = KEY_WORD + " LIKE ?";
searchString = "%" + searchString + "%";
String[] whereArgs = new String[]{searchString};
Cursor cursor = null;
if (mReadableDB == null) {
mReadableDB = getReadableDatabase();
}
cursor = mReadableDB.query(WORD_LIST_TABLE, columns, where, whereArgs, null, null, null);
return cursor;
}
and the search class is :
public void showResult(View view) {
String word = editText_search.getText().toString();
textView.setText("Result for " + word + ":\n\n");
Cursor cursor = mDataBase.search(word);
cursor.moveToFirst();
if (cursor != null & cursor.getCount() > 0) {
int index;
String result;
do {
index = cursor.getColumnIndex(mDataBase.KEY_WORD);
result = cursor.getString(index);
textView.append(result + "\n");
} while (cursor.moveToNext());
cursor.close();
} else {
textView.append("no result");
}
}
Your cursor does not return anything. this is how I usually use database in android: by using .rawQuery(); and SQLite.
e.g.
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM tasks WHERE id = " + id, null);
And you can also check if the cursor is empty or not by calling cursor.moveToFirst();.
If cursor was empty, the method returns false. else it returns true.
After checking that, you can go to the row that you want by using cursor.move(rowNumber); and get the value of the column you want with get methods e.g. cursor.getString(1);

how to use where clause in cursor query in sqlite

I want only particular rows that has "E" inside the column "TX_IDT". I used the following code but apps stops. In logcat the error says it is at db.query line.
public Cursor getAllRows( ) {
String where = null;
SQLiteDatabase db = helper.getReadableDatabase();
String[] columns = { VivzHelper.UID, helper.UID,helper.NAME,helper.TX_IDT};
String whereClause = "TX_IDT = ? ";
String[] whereArgs = new String[] { "E" };
Cursor c = db.query( VivzHelper.TABLE_NAME, columns,whereClause,whereArgs, null, null, NAME + " ASC"); // for out btn
if (c != null) {
c.moveToFirst();
}
return c;
}
`
Seems like you want record's containing "E" ,
Try this
Cursor c = db.query(VivzHelper.TABLE_NAME, columns, helper.TX_IDT +" LIKE '%E%' ", null, null, null, null);

Android SQL cursor is NULL

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

How to get the first column data in sqlite database?

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.

Bind or column index out of range, querying sqlite android table Error

I am trying to make a query to sqlite android to see for example how many users of a given username exist in a table.
This is my function. I must specify that "getContentResolver() != null" and so is variable name.
private int findSelectedUser(String name) {
int count = 0;
try {
String[] whereArgs = new String[] {name};
String[] PROJECTION = new String[] { MyProvider.SETTINGS_USERNAME };
Cursor c = getContentResolver().query(MyProvider.SETTINGS_URI,
PROJECTION, MyProvider.SETTINGS_USERNAME , whereArgs, null);
if (c != null) {
count = c.getCount();
c.close();
}
} catch (NullPointerException e) {
}
System.out.println("Found something? " + count);
return count;
}
And after running i receive the error from the subject...and don't get it. In my where clause i have one column, in my where arguments one value.
Please help me make some sence of this, Thank you.
I guess that works:
String[] whereArgs = new String[] {name};
String[] PROJECTION = new String[] { MyProvider.SETTINGS_USERNAME };
Cursor c = getContentResolver().query(MyProvider.SETTINGS_URI,
PROJECTION, MyProvider.SETTINGS_USERNAME + "=?" , whereArgs, null);
if (c != null) {
count = c.getCount();
c.close();
}
If you want to use whereArgs you have to have the same amount of ? in the where as you have items whereArgs
whereArgs will replace the ? in the final database query
String where = "name = ? OR name = ?";
String[] whereArgs = new String[] {
"Peter",
"Jim"
};
that results in name = 'Peter' OR name = 'Jim' for the query.
Btw: don't catch(NullPointerException e) - make your code safe so they can't happen

Categories

Resources