Error in cursor illegal state exception - android

I'm getting this error.
09-05 16:17:27.460: E/CursorWindow(29553): Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 8 columns.
09-05 16:17:27.465: E/AndroidRuntime(29553): FATAL EXCEPTION: main
09-05 16:17:27.465: E/AndroidRuntime(29553): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nesv.landstar/com.nesv.landstar.LandstarPage}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
I don't know what I'm doing wrong with my code. Here it is:
Cursor c = null;
try
{
c = landstarDB.rawQuery("SELECT * FROM DriverShipment", null);
}catch (Exception e) {
Log.w("Error selecting table", "Error selecting table");
}
if (c != null && c.moveToFirst()) {
c.moveToFirst();
do {
Log.i("cctid:", c.getString(c.getColumnIndex("cctid")));
if(c.getString(c.getColumnIndex("cctid")) == cctid)
{
isRecorded = true;
shipmentId = c.getString(c.getColumnIndex("cctid"));
origin = c.getString(c.getColumnIndex("origin"));
destination = c.getString(c.getColumnIndex("destination"));
protectTime = c.getString(c.getColumnIndex("protect_time"));
readyTime = c.getString(c.getColumnIndex("ready_time"));
etat = c.getString(c.getColumnIndex("eta"));
if(c.getString(c.getColumnIndex("isAccepted")) == "1")
{
isAccepted = true;
}
}
}while(c.moveToNext());
}
c.close();
Any ideas? Thanks!

column -1 tells you that there is no column cctid, and getColumnIndex returns -1.
Also
c.getString(c.getColumnIndex("cctid")) == cctid
Will not work. Strings are compared using the equals method.
I suggest you post your table creation Query so we can see why the column is not there.

You have call c.moveToFirst(); two times
if (c != null && c.moveToFirst()) {
c.moveToFirst(); // Remove this one

Change your loop as below:
if (c.getCount > 0) {
c.moveToFirst();
do {
Log.i("cctid:", c.getString(c.getColumnIndex("cctid")));
if(c.getString(c.getColumnIndex("cctid")) == cctid)
{
isRecorded = true;
shipmentId = c.getString(c.getColumnIndex("cctid"));
origin = c.getString(c.getColumnIndex("origin"));
destination = c.getString(c.getColumnIndex("destination"));
protectTime = c.getString(c.getColumnIndex("protect_time"));
readyTime = c.getString(c.getColumnIndex("ready_time"));
etat = c.getString(c.getColumnIndex("eta"));
if(c.getString(c.getColumnIndex("isAccepted")) == "1")
{
isAccepted = true;
}
}
}while(c.moveToNext());
}

Related

error show cursor out of bound

i'm show the particular data into listview bt it doenot show anything even my emulator goes blank....
the query is as..
SQLiteDatabase sd = db.getReadableDatabase();
String select = "SELECT * FROM pending_dues_table WHERE _pending_dues_id ="+i;
cr = sd.rawQuery(select, null);
if (cr != null) {
//cr.moveToFirst();
int ii;
ii=cr.getColumnIndex("pending_dues_notice");
while (cr.moveToLast()){
namelist.add(cr.getString(ii));
//studentno.add(cursor.getString(1));
}
}
ArrayList<String>combimelist=new ArrayList<String>();
for(int j = 0; j<namelist.size();j++){
combimelist.add(namelist.get(j));
}
adapter = new ArrayAdapter<String>(StudentDues.this,R.layout.student_due, combimelist);
and locat show error as..
05-25 03:33:56.225: E/AndroidRuntime(5134): FATAL EXCEPTION: main
05-25 03:33:56.225: E/AndroidRuntime(5134): java.lang.OutOfMemoryError: [memory exhausted]
05-25 03:33:56.225: E/AndroidRuntime(5134): at dalvik.system.NativeStart.main(Native Method)
Your logcat says
CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
......
at com.example.mytryapp.TeacherStudent$1.onClick(TeacherStudent.java:57)
so i think your problem is hare
if (get_rollno.equals(CR.getString(0)))
{
loginstatus = true; NAME=CR.getString(0);
}
and my suggestion is just check before call it that you must have some data.
try to do this Hope it works
if(cursor.getCount() > 0){
// get values from cursor here
if (get_rollno.equals(CR.getString(0)))
{
loginstatus = true; NAME=CR.getString(0);
}
}
or there is better way
try
Cursor cursor = //query here
while (cursor.moveToNext()) {
// retrieve values from the cursor
}
if there is any problem ... comment it

Reading row count from Cursor

How do I get the row count of a Cursor without using moveToFirst()?
(Is it possible to do .getCount() without doing .moveToFirst() ???)
Logcat
11-29 13:37:40.370: E/SQLiteLog(8459): (11) database corruption at
line 62665 of [00bb9c9ce4]
11-29 13:37:40.370: E/SQLiteLog(8459): (11) statement aborts at 44:
[select pos, definition, sample FROM word INNER JOIN sense ON
word.wordid = sense.wordid INNER JOIN synset ON sense.synsetid =
synset.synsetid LEFT JOIN sample ON sample.synsetid = syn
Code
try {
if (sqldb2 == null || !sqldb2.isOpen()) {
dbobj2 = new SqLiteConection(context,
"/mnt/sdcard/sk2.db");
sqldb2 = dbobj2.openDB2();
}
// if(sqldb2!=null){
cursor_n = sqldb2.rawQuery(NOUN, null);
cursor_n.moveToFirst();
if (cursor_n.getCount() > 0) {
if (cursor_n != null) {
if (cursor_n.moveToFirst()) {
do {
String strin = cursor_n
.getString(cursor_n
.getColumnIndex("definition"));
d_noun_List.add(strin);
} while (cursor_n.moveToNext());
searchData_DTO.setD_nounList(d_noun_List);
}
}
cursor_n.close();
}else {
break;
// record not found
}
} catch (Exception e) {
Log.d("in Exception", "reason" + e);}
Use .getCount function to get the row count
Cursor.getCount()
To get row count you can use:
cursor_n.cursor.getCount();
Done by myself by doing the backup of the db

String array index error

I use the following method, but every time i use it i got error.
I cant figure out why because i perfrom this checking
if(unWanted == null || unWanted[0] == null)
The error is in this code:
unWanted[0] == null
but if i do only
if(unWanted == null)
It doest not see unWaned as null.
Thank for helping :)
the error code:
05-12 06:24:41.293: E/AndroidRuntime(24373): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.workoutlog/com.example.workoutlog.AddWorkOutPage}: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
My method:
public void checking(){
DataBaseMain data = new DataBaseMain(this);
data.open();
String[] unWanted = data.getAllUnwantedExercies();
data.close();
if(unWanted == null || unWanted[0] == null)
Toast.makeText(this, "good", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "bad", Toast.LENGTH_LONG).show();
The method to get the String array from my DB.
public String[] getAllUnwantedExercies() {
Cursor c = ourDatabase.query(true, TABLE_NAME, new String[] {COLUMN_NOT_ON_LIST_EXERCISE}, null, null, COLUMN_NOT_ON_LIST_EXERCISE, null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_NOT_ON_LIST_EXERCISE);
if(c.getCount() < 1)
return null;
int f = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if(c.getString(dayExercise) != null && c.getString(dayExercise).equals("") == false)
f++;
}
String[] list = new String[f];
int j = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if(c.getString(dayExercise) != null && c.getString(dayExercise).equals("") == false){
list[j] = c.getString(dayExercise);
j++;
}
}
return list;
}
unWanted[0] == null
It's clear that your array has no values in it. Attempting to reference the first index of an array of length 0, as explained in your stack trace, is a run time error.
unWanted == null
This doesn't work because the array object itself is not null.
A work around
A simple solution here is, at the end of your function, check the length of the array. If it is 0, you know it has no values, and you can return null.
if(list.length == 0)
{
return null;
}
else
{
return list;
}
or more concisely:
return list.length == 0? null:list;
Then when you get your array back from your function, all you need to do is test to check if the array is null.
if(unWanted == null)
{
// Array is empty.
}
Maybe just change this line:
if(unWanted == null || unWanted[0] == null)
By this one:
if(unWanted.length <= 0)
unWanted[0] == null
Here you are trying to check the first position of your array is null or not. Instead of this check your array size is 0 or not.
if(unWanted.length==0){
// your code
}
I hope this will help you.
You need to check that the length is greater than 0. It is not null because you are returning a list albeit an empty list. So it isn't null but also doesn't have a length
unWanted is not null does not mean you can reference it is first element by using unWanter[0] because it might be an empty array.

problems with cursor and getting data?

I have created a table and trying to fetch data from it using a cursor as follow:
public Cursor getcontent() {
Cursor d = database.query(DatabaseHandler.Table_Name2,allColumns,selection, null, null,null,null);
return d;
}
Cursor r = X.getcontent();
if (r.getCount() > 0) {
r.moveToFirst();
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext()==true);
r.close();
} else {
Log.i("TAG"," No value found");
}
}
I am showing the result in the TextView to see what data it is fetched. My problem is when I run this code sometimes it shows the data in the TextView, whatever it has fetched and sometimes it doesn't. Its a 50:50 ratio, according to me it should show fetched values every time as data is fetched every time I don't know what is wrong here, can someone tell me what's the issue here?
Check Whether Cursor you are getting is Null or not . and if yes then What is the Count of Cursor. you can Do it by Below Way.
Cursor r = X.getcontent();
if ((r != null) && (r.getCount() > 0)) {
r.moveToFirst();
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext());
r.close();
} else {
Log.i("TAG"," No value found inside Cursor");
}
try like this
Cursor r = X.getcontent();
try {
if (r.moveToFirst()) {
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext());
}
} finally {
if(r!=null) {
r.close();
}
}

Cursor Exception

I have created a database and i want to retrieve some data from the database by using the cursor by i always get this error
04-19 20:02:56.747: E/AndroidRuntime(301): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
04-19 20:02:56.747: E/AndroidRuntime(301): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
04-19 20:02:56.747: E/AndroidRuntime(301): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
04-19 20:02:56.747: E/AndroidRuntime(301): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
here is the code of the function
public double getlatitude(String[] i,int x) {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_SQUAREID, KEY_SQUARELATITUDE, KEY_SQUARENAME,
KEY_SQUARELONGITUDE
};
Cursor c;
c=ourDatabase.query("squares", columns,"squarename=?",i, null, null, null);
String latitude = null;
if (c.moveToFirst()) {
latitude=c.getString(0);
}
double latitude_double=Double.parseDouble(latitude);
return latitude_double;
}
Try this
if(c.getCount() > 0) {
c.moveToFirst();
for(int i=0;i<c.getCount();i++) {
//do your logic here
}
}
The exception likely occurred because your cursor is empty (there may have been no match). To avoid this make sure that you check whether the cursor is empty or not, if it is empty then you should not try to access it. And if it is not empty, you should check the max row count and make sure that you don’t access to any row that is equal or higher than the max row count. See the code below:
if ( c != null && c.getCount() > 0 ) {
if (c.moveToFirst()) {
do {
// do something here
} while (c.moveToNext());
}
c.close();
}
I think the problem is here:
latitude=c.getString(0);
Change it to:
latitude = c.getString(c.getColumnIndex("column_name"));
and also dont forget to close your cursor before returning value by calling c.close();
Whenever you are dealing with Cursors, ALWAYS check for null and check for moveToFirst() without fail, if you want to avoid weird crashes in the future.
if( c != null ){
if( c.moveToFirst() ){
//Do your stuff
}
}
//After finishing always close the cursor.
c.close();

Categories

Resources