error show cursor out of bound - android

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

Related

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

Error in cursor illegal state exception

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());
}

Receiving unknown count of results from SQLite db

Basically this is not a problem in itself, my code works so far.
What I have is a App, that lets a user log in and depending on his ID in the db, he gets displayed his saved notes. For this view I have this part of code:
title = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
MyDbHandler dbh = new MyDbHandler(this);
for(int i = 0; i < 999; i++) {
content = dbh.getNoteTitle(id, i); //getNoteTitle(int, int) returns String
if(content != null && content != "0")
title.add(content);
else
break;
}
list.setAdapter(title);
As I said, this works so far.
Thing is - I am very unhappy with the use of ' break; ' here, as I learned during education, this shouldn't be used.
Is there a smoother way to approach this issue?
Also ' content != "0" ' should be ' ! content.equals("0") ' normally, right? But that one doesn't work then... Why is this?
I am not sure what are you trying to do. First of all you should use "equal" method for Strings. The condition "content != "0" will always be true, because you are comparing 2 different objects. The condition "! content.equals("0")" should return true most of the time (when the value is not "0") and probably you should use the debugger to see exactly what is the value of content.
Second if you want to take all the notes from the database and show them to the user you should have first a method in the SQLiteOpenHelper similar to (it is not efficient to interrogate the database for each item, plus the separation of concerns):
public ArrayList<String> getNotesList (int userID){
SQLiteDatabase db = getWritableDatabase();
Cursor c = db.query(TABLE_NAME, new String[] {MyDbHandler.COLUMN_NOTE_TITLE}, MyDbHandler.userID + "=" + userID,null, null, null, null);
ArrayList<String> list = null;
String noteTitle;
if (c != null && c.moveToFirst())
{
list = new ArrayList<String>(c.getCount());
for (int i = 0; i < c.getCount(); i++)
{
noteTitle = c.getString(c.getColumnIndex(MyDbHandler.COLUMN_SESSION_PATH));
list.add(noteTitle);
c.moveToNext();
}
}
c.close();
db.close();
return list;
I think you should not save notes that you don't want to use (e.g. null or "0"), so instead of checking here, I would check in the addNote method.
For the list initialization you have:
MyDbHandler dbh = new MyDbHandler(this);
ArrayList listData = dbh.getNotesList(id)
if (listData != null && listData.length != 0){
title = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
listData.setAdapter(title);
}
I didn't test the code, but I hope it helps you. Good luck!

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();

How to take an entire column of a database and turn it into a String array?

I'm trying to take an entire column from a table in my DB and store all the entries into a String array Below you have my code:
public Cursor fetchAllBarcodeEntries(){
return db.query(BARCODE_TABLE, new String[] {KEY_BARCODE_ID, KEY_BARCODE_NUMBER, KEY_BARCODE_PRODUCT, KEY_BARCODE_PRODUCT_DESC}, null, null, null, null, null);
}
I'm calling and using the function like this:
Cursor c = dbAdapter.fetchAllBarcodeEntries();
for(int i = 0; i < c.getCount(); i++){
stringArray[i] = c.getString(c.getColumnIndex(dbAdapter.KEY_BARCODE_PRODUCT);
}
This is part of the error log that I'm getting
01-26 23:15:02.434: E/AndroidRuntime(787): Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
Any help would this would be greatly appreciated...
The answer is here
ArrayList<String> columnArray1 = new ArrayList<String>();
ArrayList<String> columnArray2 = new ArrayList<String>();
ArrayList<String> columnArray3 = new ArrayList<String>();
if(mCursor.moveToFirst()!=null){
do{
columnArray1.add(mCursor.getString(COLUM_INDEX1));
columnArray2.add(mCursor.getString(COLUM_INDEX2));
columnArray3.add(mCursor.getString(COLUM_INDEX3));
} while (mCursor.moveToNext()!=null);
}
Afterwards you can convert the ArrayList into a String array:
String[] colStrArr1 = (String[]) columnArray1.toArray(new String[columnArray1.size()]);
You should check the return value of c.getColumnIndex(). It is probably returning -1 because the given column (dbAdapter.KEY_BARCODE_PRODUCT) does not exist in that table, possibly due to an error on your database.
Also, what's Toast.LENGTH_SHORT doing there?
It seems something is missing from the code you posted...
You may try something like this below:
Cursor c = dbAdapter.fetchAllBarcodeEntries();
int columnCnt = c.getColumnCount ();
String[] stringArray = new String[columnCnt];
c.moveTofirst();
for(int i = 0; i < columnCnt ; i++){
stringArray[i] = c.getString(i);
}
Note: I don't have IDE handy, there may be syntax errors.

Categories

Resources