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();
Related
I am trying to update the existing column of my table but am not able to do so....
There are no errors it is just not getting updated.
My code are there below
Calling the function by passing value a is the _id in which i want to change and i is the value which i want to insert.
boolean isUpdate = mDbHelper.updatedata(String.valueOf(a),String.valueOf(i));
The function which I am using to change the values
public boolean updatedata(String id,String books){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Lib_student.COLUMN_STUDENT_BOOKS,books);
Cursor cursor = db.rawQuery("select * from Library_Student where books=?",new String[]{books});
long r = db.update("Library_Student",contentValues,"books=?",new String[]{books});
if (r == -1){
return false;
}else {
return true;
}
}
Here is the table which i need to edit..
String SQL_CREATE_LIBRARY_TABLE_STUDENT = "CREATE TABLE "+ Lib_student.TABLE_NAME + " ("
+Lib_student._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+Lib_student.COLUMN_STUDENT_NAME+ " TEXT NOT NULL, "
+Lib_student.COLUMN_STUDENT_EMAIL+ " TEXT, "
+Lib_student.COLUMN_STUDENT_AGE+ " INTEGER , "
+Lib_student.COLUMN_STUDENT_GENDER+ " TEXT ,"
+Lib_student.COLUMN_STUDENT_NUMBER+ " INTEGER ,"
+Lib_student.COLUMN_STUDENT_ADDRESS+ " TEXT ,"
+Lib_student.COLUMN_STUDENT_BOOKS + " INTEGER );";
First, there is no need to select the row that you want to update, so remove this line:
Cursor cursor = db.rawQuery("select * from Library_Student where books=?",new String[]{books});
Also, you must pass the id and not the value of books as an argument to the method update():
public boolean updatedata(String id, String books) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Lib_student.COLUMN_STUDENT_BOOKS, books);
return db.update("Library_Student", contentValues, Lib_student._ID + " = ?", new String[]{id}) > 0;
}
The method update() returns the number of the updated rows (it never returns -1), so you must compare that number to 0 and return true if it is greater than 0 or false if it is 0.
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;
}
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 );
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;
}
For the life of me, I can't get the cursor to return any data. I've verified that their is data in the database and my insertions are working. The official error is:
CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
Top level declarations:
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
this.db = this.DBHelper.getWritableDatabase();
}
My function:
public String getRandomEntry()
{
int rand;
Random random = new Random();
int numEntries = (int)this.getCount();
if(numEntries == 0)
return "ERROR: Database is empty.";
rand = random.nextInt(numEntries);
Cursor cursor = DBHelper.getWritableDatabase().rawQuery(
"SELECT * FROM " + DATABASE_TABLE
+ " WHERE " + COLUMN_A + " = " + 0, null);
Log.i("numEntries", Integer.toString(numEntries));
Log.i("rand", Integer.toString(rand));
Log.i("cursor", Integer.toString(cursor.getCount()));
cursor.moveToFirst();
return cursor.getString(0);
}
I've also tried grabbing the cursor as such:
Cursor cursor = db.rawQuery(
"SELECT * FROM " + DATABASE_TABLE
+ " WHERE " + COLUMN_A + " = " + 0, null);
Please give me your thoughts! Thank you!!
Nothing seems random here at all. It appears that you are looking for column_a with a value of 0 every time.
I would assume that column_a has nothing with a value of 0.
First of all try to query this way:
String args[] = new String[]{"0"};
Cursor cursor = db.rawQuery(
"SELECT * FROM " + DATABASE_TABLE + " WHERE " + COLUMN_A + " = ?", args);
If this not helps check your db with external tool if you query return rows there.