I'm trying to get records in my table. I'm using this code
if(c!=null){
if(c.moveToFirst()) {
String tipId = c.getString(c.getColumnIndex(DAO.TIP_ID)).toString().trim();
System.out.println("tipId: "+ tipId);
}else{
// Handle no rows returned
System.out.println("Handle no rows returned");
}
}else{
System.out.println("debug Cursor , cannot be created");
}
But it gives me the following exception
Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
and it refers to that line:
String tipId = c.getString(c.getColumnIndex(DAO.TIP_ID)).toString().trim();
hope anyone helps me to fix this.
Thanks in advance.
In your code
c.getColumnIndex(DAO.TIP_ID)
is returning -1. This means value of DAO.TIP_ID doesnot match with any column name of table .Check if this value is correct and matches with a column name of the table you are accessing
add following line before the line which causes problem and post the Logcat output here
Log.v("out-data",DAO.TIP_ID+" "+c.getColumnIndex(DAO.TIP_ID)+" "+c.getColumnName(0));
(add import statement import android.util.Log; in beginning of your
code)
The query selection does not contain the column DAO.TIP_ID.
You should fix this to solve this error message
"Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it."
it works in my code.
Try to position cursor by moveToFirst before reading data from it.
check for null. e,g; if (c != null && c.moveToFirst()) {}
check for count. e,g; (c != null && c.getCount() >0 && c.moveToFirst()){}
Related
I am trying to insert data into a SQLite DB once a notification is received via FCM. For debugging purpose I am also inserting a dummy data into my DB when SHow Token is clicked on the HomeScreen activity.
However am getting
"I am getting "Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it."
Link to my code: - GitHub
Can someone please go through my code and let me know where I am going wrong.
Note - I added below in HomeScreen.java,MyFirebaseMessagingService.java and NotificationDetails.java
private SQLiteDB dbHelper = new SQLiteDB(this);
since the suggested
private SQLiteDB dbHelper;
did not work for me
When I used above I kept on getting Nullpointer exception, so I figured since the SQLiteDB class constructor is accepting a context, so let me pass one, post which I did not get NullPointer Exception.
Now I did this without being fully aware of the concept on context which I have been trying to wrap my head around, but since am an extreme noob to android I am not able to grasp it just yet. I suspect it might have something to do with the context I am passing.
Can someone please help me here with detailed instructions on how to fix this issue, I have been through many other threads on this but was not able to fix hence after 5 hrs of going through multiple SO questions, I am posting this one.
Thanks in advance to everyone in the community for the help. :)
Edit
Upon suggestion by admins, I am including below snippet of my code.
Where I am calling the cursor
dbHelper.insertNotification("This is a notification");
//Check if the message contains data
Cursor rs = dbHelper.getAllNotifications();
rs.moveToFirst();
token_text.setText("Token: " +rs.getString((rs.getColumnIndex("NOTIFICATION_DETAILS"))));
Insert Notification Function in SQLiteDB.java
public boolean insertNotification(String notification){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NOTIFICATION_DETAILS,notification);
db.insert(NOTIFICATION_TABLE_NAME,null,contentValues);
return true;
}
getAllNotifications function
public Cursor getAllNotifications() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery( "SELECT * FROM " + NOTIFICATION_TABLE_NAME, null );
return res;
}
Couldn't read row 0, col -1 from CursorWindow.
Is saying that you are attempting to get the column at offset -1 from row 0 (the first row). So you have provided an invalid offset (it cannot be an offset of -1, the offset must be 0 or greater and the maximum value will be 1 less than the number of columns in the Cursor).
The most likely cause, is that Cursor method getColumnIndex(the_column_name_as_a_string) will return -1 when the column passed to the method cannot be found in the Cursor. Noting that due to a bug column name is case sensitive.
As such your issue is that the Cursor does not contain a column name NOTIFICATION_DETAILS and as you have used * (all columns) then that column does not exist in the table.
By the looks of it you should be using the String variable NOTIFICATION_DETAILS so you probably need to use :-
token_text.setText("Token: " +rs.getString((rs.getColumnIndex(NOTIFICATION_DETAILS)))); //<<<<<<<<<< double quotation marks removed.
Additional
You should NEVER assume that moveToFirst (or any Cursor move???? method) actually does the move. You should ALWAYS check the returned value. It will be true if the move was successful otherwise it would be false.
Again note that the column name passed to the getColumnIndex method is case dependant.
As such you should use something like
:-
dbHelper.insertNotification("This is a notification");
//Check if the message contains data
Cursor rs = dbHelper.getAllNotifications();
if (rs.moveToFirst()) {
token_text.setText("Token: " +rs.getString((rs.getColumnIndex(NOTIFICATION_DETAILS))));
} else {
........ code here if anything need to be done if there are no rows extracted
}
Addition re comment :-
Cursor rs = dbHelper.getAllNotifications(); rs.moveToFirst(); do{ for
(int i = 0; i < rs.getColumnCount(); i++) {
notification_array.add(rs.getString((rs.getColumnIndex(NOTIFICATION_DETAILS))));
} }while (rs.moveToNext());
using the following is much simpler :-
Cursor rs = dbHelper.getAllNotifications();
while (rs.moveToNext()) {
notification_array.add(rs.getString((rs.getColumnIndex(NOTIFICATION_DETAILS))));
}
in my activity ineed to check whether the table exist or not for that im using
Cursor cursor = marksdb.rawQuery("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='"+classt+"'", null);
im getting 1 if table exist 0 otherwise
for that i need check value in cursor for that im using
if(cursor.getCount()==1){
// get values from cursor here
callclasstb();
}
else{
tv.setVisibility(View.VISIBLE);
subjectet.setEnabled(false);
markset.setEnabled(false);
markssp.setEnabled(false);
}
but in all cases im getting value 1 because getcout() returns a value 1 r 0 and
callclasstb();
is not executing what condition i need to write in if{....} to make it execute
cursor.getCount() in your case will always return 1 (the number of "rows" in your resultset). you need to figure out what was returned via the cursor.
Cursor cursor = marksdb.rawQuery(...);
cursor.moveToFirst(); // first "row"
int nTableExists = cursor.getInt(0);
cursor.close();
if (nTableExists) { // != 0
...do something...
}
I am using custom adapter extending cursor adapter for displaying data in listview, to display particular phone number i have passed the id to a method in database class but it is showing
errorandroid.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
while placing debugger in the the method it is not going after the line
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
Can any one help me to solve it.
This is the code:
public String getNumberFromId(int id)
{
String num;
db= this.getReadableDatabase();
Cursor cursor = db.query(scheduletable, new String[] { "ContactNumber" },"_id="+id, null, null, null, null);
cursor.moveToFirst();
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
cursor.close();
db.close();
return num;
}
Whenever you are dealing with Cursors, ALWAYS check for null and check for moveToFirst() without fail.
if( cursor != null && cursor.moveToFirst() ){
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
cursor.close();
}
Place logs appropriately to see whether it is returning null or an empty cursor. According to that check your query.
Update Put both the checks in a single statement as mentioned by Jon in the comment below.
Update 2 Put the close() call within the valid cursor scope.
try this.. this will avoid an Exception being thrown when the cursor is empty..
if(cursor != null && cursor.moveToFirst()){
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
cursor.close();
}
First check this Condition before fetching data
if(cursor!=null && cursor.getCount()>0){
cursor.moveToFirst();
num = cursor.getString(cursor.getColumnIndex("ContactNumber"));
}
Check the return value from moveToFirst(), before you try to read anything from the cursor. It looks as if no results are being returned.
a save schema to query Cursors is
// just one
Cursor cursor = db.query(...);
if (cursor != null) {
if (cursor.moveToFirst()) {
value = cursor.getSomething();
}
cursor.close();
}
// multiple columns
Cursor cursor = db.query(...);
if (cursor != null) {
while (cursor.moveToNext()) {
values.add(cursor.getSomething());
}
cursor.close();
}
In case people are still looking:
Instead of searching for "ContactNumber" try searching for Phone.NUMBER. The tutorial has the code with more details: http://developer.android.com/training/basics/intents/result.html
try to uninstall the app and then again test it... actually the sqlite db is created only once when the app is first install... so if you think your logic is current then reinstalling the app will do the trick for you. !!!!
I have tried to figure this out and googled through a fair few stack overflow responses but none of them seem to address this exact problem. I am trying to return the row ID so that I can update my database.
String query= "SELECT * FROM climb_tbl WHERE climb_name ='"+climbname+"'";
Cursor cur = db.rawQuery(query, null);
cur.moveToFirst();
long id = cur.getLong(cur.getColumnIndex("_id"));
System.out.println(id);
As far as I can tell this should return the id value I need to then run the update statement, ive yet to write. Instead I get the error.....
java.lang.IllegalStateException: get field slot from row 0 col -1 failed.
Do you have _id column in your table?
Probably the cursor is empty. The cur.moveToFirst() returns true or false, so you can use it in the following way:
if (cur != null && cur.moveToFirst()) {
long id = cur.getLong(cur.getColumnIndex("_id"));
System.out.println(id);
}
This is my query in sqlite3 by adb shell:
sqlite> SELECT round FROM prizes GROUP BY round;
100-7
However, I got a problem when translating it into Java code:
LinkedList<String> result = new LinkedList<String>();
Cursor cursor = db.rawQuery("SELECT round FROM prizes GROUP BY round", null);
if(cursor.moveToFirst()) {
do {
result.add(cursor.getString(1));
} while (cursor.moveToLast());
}
if (cursor != null && !cursor.isClosed())
cursor.close();
return (String[]) result.toArray();
When I run this code, I got an error:
ERROR/AndroidRuntime(10540): java.lang.IllegalStateException: get field slot from row 0 col 1 failed
This is because you have only 1 column returned form your query (round) and the index is zero-based
See the doc about getString
Returns the value of the requested column as a String. The result and
whether this method throws an exception when the column value is null
or the column type is not a string type is implementation-defined.
Parameters
columnIndex the zero-based index of the target column.
The below should work:
result.add(cursor.getString(0));
I believe it should be cursor.getString(0) since its a 0-based index.