How to search a column in sqlite by a string - java

I would like to return a true / false value when the string match with the column of sqlite. How can I implement the search function?
How to use cursor to do searching?
public boolean searchLuggage(String code) {
ArrayList<String> luggageCheck = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
try {
Cursor cursor = db.query(true, TABLE_LUGGAGES, new String[] { your field list }, SearchColumnname + "='" + code + "'", null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
luggageCheck.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LUGGAGE_TABLE = "CREATE TABLE " + TABLE_LUGGAGES + "(" + KEY_NAME + " TEXT NOT NULL," + KEY_CODE + " TEXT NOT NULL," + KEY_NUMBER + " TEXT NOT NULL );";
db.execSQL(CREATE_LUGGAGE_TABLE);
}

Replace this
Cursor cursor = db.query(true, TABLE_LUGGAGES, new String[] { your field list }, SearchColumnname + "='" + code + "'", null, null, null, null, null);
with this
Cursor cursor = db.query(true, TABLE_LUGGAGES, null, SearchColumnname + "= ?", new String[] { code }, null, null, null, null);

Related

How to get row cursor with primary key android

I have a table with the following
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL( "CREATE TABLE " + TABLE_NAME + " (" + "ID" + " INTEGER PRIMARY KEY," +
COLUMN_TOPIC + " TEXT," + COLUMN_LOCATION + " TEXT)");
}
I am trying to get all the data at a given rowid
public void getRowCursor(int position){
SQLiteDatabase database = getWritableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " +
"ID" + "=" + String.valueOf(position), null);
cursor.moveToFirst();
cursor.close
//or
Cursor cursor = database.query(TABLE_NAME, null, "ID", new String[]{
String.valueOf(position)}, null, null, null, null );
cursor.moveToFirst();
cursor.close
database.close
}
I get an error
java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
I did populate the table. How do I return a cursor based on the position of entry.
How do I return a cursor based on the position of entry
First, your method getRowCursor() should return a Cursor.
Also, you should not close the returned cursor because I assume that you want to use its results somehow.
Your code with the method rawQuery() should work like this:
public Cursor getRowCursor(int position) {
SQLiteDatabase database = getWritableDatabase();
String sql = "SELECT * FROM " + TABLE_NAME + " WHERE ID = " + String.valueOf(position);
Cursor cursor = database.rawQuery(sql, null);
// cursor.moveToFirst();
return cursor;
}
But, the safe and recommended way to pass parameters to a query is with ? placeholders instead of concatenating them inside the sql statement and passing them as array items in the 2nd argument of rawQuery():
public Cursor getRowCursor(int position) {
SQLiteDatabase database = getWritableDatabase();
String sql = "SELECT * FROM " + TABLE_NAME + " WHERE ID = ?";
Cursor cursor = database.rawQuery(sql, new String[] {String.valueOf(position)});
// cursor.moveToFirst();
return cursor;
}
Note that moveToFirst() moves the cursor's index at the 1st row of the cursor (if it exists).
I commented out this call, because you should use it after you call getRowCursor() like this:
Cursor cursor = getRowCursor(10); // or any other ID
if (cursor.moveToFirst()) { // the cursor contains at least 1 row
....
} else { // the cursor is empty
....
}
and when you are done with the cursor:
cursor.close();

Android studio SQL - How to return data in a string array

I have an SQL method here. I would like to return the data in a String[] array.
How do I do that exactly?
Thank you!
public String[] getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
String[] LikeSong;
Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
while (cursor.moveToNext()) {
String note = cursor.getString(0);
}
cursor.close();
db.close();
return LikeSong;
}
You must define the array's length and this can be done only after the Cursor fetches all the rows. Then set its length to the nimber of rows of the Cursor.
Then inside the while loop set the items of the array:
public String[] getLikedSongs() {
String[] LikeSong = null;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
if (cursor.getCount() > 0) {
LikeSong = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
LikeSong[i] = cursor.getString(0);
i++;
}
}
cursor.close();
db.close();
return LikeSong;
}

How to send parameter to where clause in a Sqlite query

I'm trying to get a single row from database.But it is not generated query. The questions marks still seems. What am i missing ?
public static User getSingleUser(String email,String password)
{
User user = new User();
SQLiteDatabase db = DatabaseManager.getInstance().openDatabase();
String selectQuery = " SELECT * FROM " + User.TABLE + " WHERE "
+ User.KEY_EMAIL + "=?"+ " AND " + User.KEY_PASSWORD
+ "=?" ;
Cursor cursor = db.rawQuery(selectQuery,new String[]{email,password},null);
if (cursor.moveToFirst()) {
do {
user.setId(cursor.getInt(cursor.getColumnIndex("UserId")));
user.setFirstname(cursor.getString(cursor.getColumnIndex("Firstname")));
user.setLastname(cursor.getString(cursor.getColumnIndex("Lastname")));
user.setEmail(cursor.getString(cursor.getColumnIndex("Email")));
user.setPassword(cursor.getString(cursor.getColumnIndex("Password")));
user.setIsActive(cursor.getInt(cursor.getColumnIndex("IsActive")));
} while (cursor.moveToNext());
}
return user;
}
}
Try this,
String selection = User.KEY_EMAIL + "=?"+ " AND " + User.KEY_PASSWORD + "=?";
String[] selectionArgs = new String[]{ email, password };
Cursor cursor = db.query(User.TABLE, null, selection, selectionArgs, null, null, null);
try to use native android query as below -
Cursor cursor = db.query(User.TABLE, null, User.KEY_EMAIL + "=? and " + User.KEY_PASSWORD + "=?", new String[] {email, password}, null, null, null );

Search through SQLite database on Android Search

Method causing error inside my ContentProvider
public static Cursor getSuggestions(String query) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
db.beginTransaction();
try {
String selection = Formula.FORMULA_NAME + " LIKE %?%";
String[] selectionArgs = { query + "*" };
Cursor cursor = dbHelper.getReadableDatabase().query(
FORMULA_TABLE_NAME,
new String[] { BaseColumns._ID,
SearchManager.SUGGEST_COLUMN_TEXT_1,
BaseColumns._ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID
},
selection,
selectionArgs, null, null, null);
db.setTransactionSuccessful();
return cursor;
} catch (SQLiteException e) {
} finally {
db.endTransaction();
}
throw new SQLException("Failed to begin transaction");
}
Database creation:
db.execSQL("CREATE TABLE " + FORMULA_TABLE_NAME + " (" +
BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
SearchManager.SUGGEST_COLUMN_TEXT_1 + " TEXT," +
Formula.CATEGORY + " TEXT" +
");");
Constants used:
public static final String FORMULA_NAME = SearchManager.SUGGEST_COLUMN_TEXT_1;
public static final String CATEGORY = "category";
The problem is that in my method, the transaction is unsuccessful because it throws the error: throw new SQLException("Failed to begin transaction"); What I'm trying to do is to search through the database as part of a search. When the user activates the search box, then I have it set up so that this method should be returning a cursor with the suspected items based on their name. Through debugging, I deduced that the problem was with the method of search inside my Content Provider. Any solutions or thoughts?
I'm guessing the line throw new SQLException("Failed to begin transaction"); is meant to be inside your catch block.
What if we simplify everything to:
public static Cursor getSuggestions(String query) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selection = Formula.FORMULA_NAME + " LIKE %?%";
String[] selectionArgs = { query + "*" };
Cursor cursor = db.query(
FORMULA_TABLE_NAME,
new String[] { BaseColumns._ID,
SearchManager.SUGGEST_COLUMN_TEXT_1,
BaseColumns._ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID
},
selection,
selectionArgs, null, null, null);
return cursor;
}

problem with reading contacts in android

i'm trying to read contacts with this code but it only gets Contacts but not contacts data.Please
tell me am i going on a wrong path or what is wrong with this.
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while(contacts.moveToNext()) {
int contactIdColumnIndex = contacts.getColumnIndex(ContactsContract.Contacts._ID);
long contactId = contacts.getLong(contactIdColumnIndex);
System.out.println(contactId);
Cursor c = getContentResolver().query(Data.CONTENT_URI,
new String[] {Data._ID, Phone.NUMBER, Phone.TYPE},
Data.CONTACT_ID + "=?" + " AND "
+ Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'",
new String[] {String.valueOf(contactId)}, null);
//retrieving data
while(c.moveToNext()){
long Id=c.getLong(0);
String number=c.getString(1);
String type=c.getString(2);
String name=c.getString(3);
System.out.println(Id);
System.out.println(number);
System.out.println(type);
System.out.println(name);
}
c.close();
}
contacts.close();
This runs well when i debug this and it only print ContactIds only
1
2
3
4
but no data...(apologize for long question)
try this code
String number = "";
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
for(int i=0;i<pCur.getColumnCount();i++)
number = pCur.getString(i);
}
pCur.close();
pCur = null;
}
}
}
cur.close();
cur = null;
cr = null;

Categories

Resources