I have table in sqlite that contain only one record and I want to access that in cursor but facing problem I got this exception java.lang.IllegalStateException: get field slot from row 0 col -1 failed
My code is here :
c2=sql.dis();
c2.moveToFirst();
name = c2.getString(c2.getColumnIndex(DbManager.displayname));
ListName.setText("selected list"+name);
}
and this in BD class:
public Cursor dis() {
try
{
SQLiteDatabase db= this.getWritableDatabase();
String[] todo = new String[] {displayName };
Cursor cursor=db.query(displayname, todo, null, null, null,null, null);
return cursor;
}
catch(Exception ex)
{
str = ex.toString();
}
problem of above code is in this line
name = c2.getString(c2.getColumnIndex(DbManager.displayname)); displayname is table name not a column name.
Related
I am working on a SQLite program and getting an error saying
2019-07-14 21:07:37.465 13538-13538/? E/CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 2 columns.
2019-07-14 21:07:37.466 13538-13538/? D/AndroidRuntime: Shutting down VM
2019-07-14 21:07:37.467 13538-13538/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.xyz.sqlitelist, PID: 13538
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.xyz.sqlitelist/com.example.xyz.sqlitelist.MainActivity}: java.lang.IllegalStateException:
Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
.
.
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
W/ActivityManager: Force finishing activity com.example.xyz.sqlitelist/.MainActivity
String databaseToString(){
StringBuilder dbString= new StringBuilder();
SQLiteDatabase db = getWritableDatabase();
String query=" SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
Cursor c=db.rawQuery(query,null);
c.moveToFirst();
while (!c.isAfterLast()){
if(c.getString(c.getColumnIndex("productname")) != null) {
c.moveToNext();
dbString.append(c.getString(c.getColumnIndex("productname")));
dbString.append("\n");
}
c.close();
db.close();
return dbString.toString();
}
Your column's name is "_productname" and not "productname" and this problem can be solved by not hardcoding this name since you have it in the variable COLUMN_PRODUCTNAME.
Also your code will miss rows because you use incorrectly moveToFirst(), moveToNext() and isAfterLast() when you only need moveToNext():
String databaseToString() {
StringBuilder dbString = new StringBuilder();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
Cursor c = db.rawQuery(query, null);
int index = c.getColumnIndex(COLUMN_PRODUCTNAME);
while (c.moveToNext()) {
dbString.append(c.getString(index)).append("\n");
}
c.close();
db.close();
return dbString.toString();
}
Also that WHERE 1 in the sql statement is not needed unless you want to change it later to something meaningful.
you can change your code
String sql = " SELECT * FROM " + TABLE_PRODUCTS + " WHERE 1";
Cursor c = getWritableDatabase().rawQuery(sql, null);
while (c.moveToNext()) {
if(c.getString(c.getColumnIndex("productname")) != null)
{
dbString.append(c.getString(c.getColumnIndex("productname")));
dbString.append("\n");
}
}
c.close();
db.close();
return dbString.toString();
I want to get the first name, middle name and last name of a student whose userid is used for login. I have written this particular piece of code but it stops my application.
I have used both the ways like database.query() and .rawquery() also.
Cursor studentData(String userId) {
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.query(studentTable, new String[] { "First_Name", "Middle_Name", "Last_Name"}, "User_ID=?", new String[] { userId }, null, null, null, null);
// Cursor cursor = db.rawQuery("select First_Name, Middle_Name, Last_Name from Student_Table where User_ID =?", new String[]{userId});
String data = cursor.getString(cursor.getColumnIndex("First_Name"));
db.close();
return cursor;
}
I should get whole name in the string.
You have a number of issues.
Attempting to use String data = cursor.getString(cursor.getColumnIndex("First_Name"));,
will result in an error because you have not moved the cursor beyond BEFORE THE FIRST ROW and the attempt to access the row -1 will result in an exception (the likely issue you have encountered).
you can use various move??? methods e.g. moveToFirst, moveToNext (the 2 most common), moveToLast, moveToPosition.
Most of the Cursor move??? methods return true if the move could be made, else false.
You CANNOT close the database and then access the Cursor (this would happen if the issue above was resolved)
The Cursor buffers rows and then ONLY when required.
That is The Cursor is when returned from the query method (or rawQuery) at a position of BEFORE THE FIRST ROW (-1), it's only when an attempt is made to move through the Cursor that the CursorWindow (the buffer) is filled (getCount() included) and the actual data obtained. So the database MUST be open.
If you want a single String, the full name, then you could use :-
String studentData(String userId) { //<<<<<<<<<< returns the string rather than the Cursor
SQLiteDatabase db = getWritableDatabase();
String rv = "NO NAME FOUND"; //<<<<<<<<<< value returned if no row is located
Cursor cursor = db.query(studentTable, new String[] { "First_Name", "Middle_Name", "Last_Name"}, "User_ID=?", new String[] { userId }, null, null, null, null);
if (cursor.modeToFirst()) {
String rv =
cursor.getString(cursor.getColumnIndex("First_Name")) +
" " +
cursor.getString(cursor.getColumnIndex("Middle_Name")) +
" " +
cursor.getString(cursor.getColumnIndex("Last_Name"));
}
cursor.close(); //<<<<<<<<<< should close all cursors when done with them
db.close(); //<<<<<<<<<< not required but would result in an exception if returning a Cursor
return rv;
}
Or alternately :-
String studentData(String userId) { //<<<<<<<<<< returns the string rather than the Cursor
SQLiteDatabase db = getWritableDatabase();
String rv = "NO NAME FOUND"; //<<<<<<<<<< value returned if no row is located
Cursor cursor = db.query(studentTable, new String[] { "First_Name"||" "||"Middle_Name"||" "||"Last_Name" AS fullname}, "User_ID=?", new String[] { userId }, null, null, null, null);
if (cursor.modeToFirst()) {
String rv =
cursor.getString(cursor.getColumnIndex("fullname"));
}
cursor.close(); //<<<<<<<<<< should close all cursors when done with them
db.close(); //<<<<<<<<<< not required but would result in an exception if returning a Cursor
return rv;
}
the underlying query being SELECT First_Name||" "||Middle_Name||" "||LastName AS fullname FROM student_table; so you concatenate the names as part of the query which returns just one dynamically created column named fullname.
I wanna get the sum of KEY_REC_VAL from table MMDatabaseHelper.TABLE_RECORD. My code is resulting in fatal error and I have no idea how to solve it. Any ideas? Thank you.
public Integer getIncomesSum()
{
String col = MMDatabaseHelper.TABLE_RECORD+"."+MMDatabaseHelper.KEY_REC_VAL;
String whereClause = " WHERE " +TABLE_RECORD+"."+KEY_REC_VAL+" >"+" 0";
String query = "SELECT sum ("+col+
") FROM "+TABLE_RECORD+
whereClause;
Log.i("SQL",query);
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(query,null);
} catch (SQLiteException e) {
} finally {
} return cursor.getInt(0);
Here is the error:
ERROR: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
before return statement add this line cursor=cursor.moveToFirst();
I want to check the records are available or not in my Sqlite table. I tried but the cursor is always return 1 value even if the SQlite databse table is empty, no any record in table. Why return one? How to solve this issue?
dbhelper = new MyDbHelper(this);
SQLiteDatabase db = dbhelper.getWritableDatabase();
String count = "select count(*) from ActivityObjectList";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
if(icount>0)
{
Log.e("Record does not found","");
//leav
}
else
{
Log.e("Record is exists !!","");
//populate table
}
Use mcursor.getCount() to check number of rows.
I use one in my sqlite database a config table. This has the following composition:
private static final String DATABASE_CONFIG_CREATE =
"CREATE TABLE " + TABLE_CONFIGS
+ "("
+ CONFIG_HIDDEN_CATEGORIES + " TEXT DEFAULT '1,2' NULL"
+ ");";
Later I try to access with the following code:
Cursor cursor = database.query(DatabaseHelper.TABLE_CONFIGS, new String[] {DatabaseHelper.CONFIG_HIDDEN_CATEGORIES}, null, null, null, null, null);
try {
cursor.moveToFirst();
int test = cursor.getCount();
String data = cursor.getString(0);
}
catch (Exception exception) {
But the line cursor.getString(0) throws the following exeption (variable test is 0):
android.database.CursorIndexOutOfBoundsException: Index 0 requested,
with a size of 0
when I run the following code, the column CONFIG_HIDDEN_CATEGORIES is displayed to me... what is wrong?
Cursor dbCursor = database.query(DatabaseHelper.TABLE_CONFIGS, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames(); // index 0 is the value of CONFIG_HIDDEN_CATEGORIES
It means that your Cursor is empty. You should wrap your actions to correct condition:
try {
if (cursor.moveToFirst()) {
String data = cursor.getString(cursor.getColumnIndex("columnName"));
// do your stuff
}
else {
// cursor is empty
}
}
...
Your actual code won't work correct because you just calling moveToFirst() method but you don't know (are not testing) if it'll return true or false.
Your code works correct only if Cursor is not empty. In second case it won't work.
Note: I recommend you to use getColumnIndex(<columnName>) method for getting column index due to its name. This method is safer and more human-readable.