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 );
Related
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();
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;
}
hi i m fetching the all entries of today date i write the query for that but i did not get the correct entries. please solve my issue .below i write my code.thank you.
public ArrayList<groups> fetchByTodayDate(){
String selectQuery = "SELECT * FROM " + DatabaseHelper.TABLE + " WHERE "+ DatabaseHelper.DATETIME + "<=date('now')";
Cursor cursor = database.rawQuery(selectQuery,null);
ArrayList<groups> all = new ArrayList<groups>();
if (cursor != null && cursor.moveToFirst()) {
do {
groups data = new groups();
smsdata.setMsgtext(cursor.getString(cursor.getColumnIndex(DatabaseHelper.TEXTMSG)));
smsdata.setSmsId(cursor.getString(cursor.getColumnIndex(DatabaseHelper._ID)));
all.add(data);
} while (cursor.moveToNext());
}
cursor.close();
return all;
}
("SELECT * FROM " + table_name + " WHERE " + KEY_DATE + "='" + date + "'", null);
Try this solution for today's entries:-
String selectQuery = "SELECT * FROM " + DatabaseHelper.TABLE + " WHERE date(datetime("+ DatabaseHelper.DATETIME+"/1000, 'unixepoch','localtime'))=date('now')";
Try this
public ArrayList<groups> fetchByTodayDate()
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<groups> all = new ArrayList<>();
String selectQuery = "SELECT * FROM " + DatabaseHelper.TABLE;
Cursor cursor = db.rawQuery(selectQuery,null);
cursor.moveToFirst ();
while (!cursor.isAfterLast())
{
all.add(new groups (
cursor.getString(cursor.getColumnIndex(DatabaseHelper.TEXTMSG)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper._ID))
));
cursor.moveToNext ();
}
cursor.close();
db.close();
return all;
}
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);
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;
}