Two Cursors, ListView, CursorIndexOutOfBoundsException - android

As a beginner in android java world I need your help. I've got problem with famous "CursorIndexOutOfBoundsException".
I'm using SQLite db, and I have two cursors, I'm getting some rows from database.
I need to get some previous values with some conditions with second cursor (c2) and put these values on ListView.
Code works with one exception:
"android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0".
ListView looks OK if I just ignore this exception but I want to fix it.
I know it is connected to with Cursor. I tried to check some conditions - it didn't help. Maybe if you could take a look at my code you find where is the cause.
Code:
public void LoadLogGrid()
{
dbHelper=new DatabaseHelper(this);
try
{
int LogName = (int) spinLog.getSelectedItemId();
Cursor c=dbHelper.getLogByLogID(LogName);
if (c != null) c.moveToFirst();
int count = c.getCount();
if (c.moveToFirst()){
ArrayList<String> mArrayList = new ArrayList<String>();
int i=0;
do {
int sVar1 = c.getInt(c.getColumnIndex("Var1"));
Long sId = (long) c.getInt(c.getColumnIndex("_id"));
Cursor c2=dbHelper.getPrevLogByLogID(LogName,sVar1);
c2.moveToFirst();
if (c2!=null) {
String sPrevOdo = c2.getString(c2.getColumnIndex("Odo"));
mArrayList.add(sPrevOdo);
c2.close();
} else {
//stopManagingCursor(c2);
//c2.close();
Log.d("A:", "Something");
}
String [] from=new String []{"Date","Col1","Col2","Col3"};
int [] to=new int [] {R.id.logDate,R.id.logCol1,R.id.logCol2,R.id.logCol3,R.id.rowOpt2};
SimpleCursorAdapter sca=new LogCursorAdapter(this,R.layout.loggridrow,c,from,to,mArrayList);
grid.setAdapter(sca);
registerForContextMenu(grid);
i++;
} while (c.moveToNext());
c.close();
dbHelper.close();
}
}
catch(Exception ex)
{
AlertDialog.Builder b=new AlertDialog.Builder(this);
b.setMessage(ex.toString());
b.show();
}
}
Query in second cursor:
public Cursor getPrevLogByLogID(long LogID, long Var1)
{
SQLiteDatabase db=this.getReadableDatabase();
String[] params=new String[]{String.valueOf(LogID),String.valueOf(Var1)};
Cursor c2=db.rawQuery("SELECT LogID as _id, Col1 from Log WHERE Col2=? AND Col3<? AND Full=1 ORDER BY Odo DESC", params);
if (c2 != null) { c2.moveToFirst();}
return c2;
}

Try changing your
do {
....
} while (c.moveToNext());
to
while (c.moveToNext()) {
....
}
The way it is now, it will run the loop at least once no matter what.

you have moved the c2 to the position as c2.moveToFirst() and after that you are doing the checking process whether it is null or not and i think the cursor should be null so that the exception is raised try putting the checking condition before moving the cursor to the first position

Related

Android Studio: Unable to print cursor results

I am attempting to print the cursor results to log.d.
When I print the results of the cursor, it does not print the array.
i.e. D/Row values: com.example.androidlabs.Todo#7c9655f
Here is the code:
public void printCursor(Cursor c) {
//The database version number using db.getVersion for the version number.
int version = db.getVersion();
//The number of rows in the cursor
int rowCount = c.getCount();
//The number of columns in the cursor
int columnCount = c.getColumnCount();
//The names of the columns in the cursor
String[] columnNames = c.getColumnNames();
//The results of each row in the cursor
ArrayList<Todo> rowValuesList = new ArrayList<>();
int ColIndex = c.getColumnIndex(myOpener.COL_1);
int itemColIndex = c.getColumnIndex(myOpener.COL_2);
int urgentColIndex = c.getColumnIndex(myOpener.COL_3);
c.moveToFirst();
if(c.moveToFirst()) {
long id = c.getLong(ColIndex);
String item = c.getString(itemColIndex);
int urgentInt = c.getInt(urgentColIndex);
if (urgentInt == 1) {
urgent = true;
} else {
urgent = false;
}
rowValuesList.add(new Todo(item, urgent, id));
}
String rowValues = TextUtils.join(",", rowValuesList);
//Printing variables to log
Log.d("Database version", String.valueOf(version));
Log.d("Row count", String.valueOf(rowCount));
Log.d("Column count", String.valueOf(columnCount));
Log.d("Column names", Arrays.toString(columnNames));
Log.d("Row values", rowValues);
}
Other options I have tried that have not worked:
Log.d("Row values", rowValuesList.toString());
for (Todo t : rowValuesList) {
Log.d("Row values", String.valueOf(t));
}
StringBuilder s = new StringBuilder();
for(Todo todo : rowValuesList) {
s.append(todo);
s.append(",");
}
Log.d("Row values", String.valueOf(s));
I know the cursor is not empty as it is displays the results when loaded from SQLite on the application.
Any advice would be helpful.
Thank you,
Your output is:
D/Row values: com.example.androidlabs.Todo#7c9655f
That would make sense if:
rowValuesList contains a single Todo object, and
Your Todo class does not have a custom implementation of toString()
The default implementation of toString() that you inherit from Object gives a result like what you see: the fully qualified class name and an object ID, separated by #.

I need help for getting SQLite data

I use this method for retrieving my data
public String getdata() {
String[] columns= new String[]{RowId,RowBusinessName};
Cursor c=OurDatabase.query(TableName,columns,null,null,null,null,null);
String Result="";
int iRowId=c.getColumnIndex(RowId);
int iRowBusinessName=c.getColumnIndex(RowBusinessName);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
Result=Result+c.getString(iRowBusinessName)+"\n";
}
return Result;
}
How can I make it return structured data (id & business_name)?
I want to display every business_name in a single textview.
Please help
If I understand what you are trying to do, here is the solution if you want to get only 1 RowBusinessName returned as a String. (Hoping that your RowBusinessName is type String).
public String getdata(int rowId) {
String[] columns= new String[]{RowId,RowBusinessName};
Cursor cursor = db.query(TABLENAME, columns, RowId + "=?", new String[]{rowId + ""}, null, null, null, null);
String Result="";
if (cursor != null && cursor.moveToFirst()) {
// not required though
int rowId = cursor.getInt(cursor.getColumnIndexOrThrow(RowId));
String rowBusinessName = cursor.getString(cursor.getColumnIndexOrThrow(RowBusinessName));
result = rowBusinessName;
}
return result;
}
Now if you want a list of RowBusinessName, then you have to build a List<String> rather than appending it to Result. That's not really a good way!
public List<String> getAll() {
List<String> businessNameList = new ArrayList<String>();
String[] columns= new String[]{RowId,RowBusinessName};
Cursor c=OurDatabase.query(TableName,columns,null,null,null,null,null);
if (c != null && c.moveToFirst()) {
// loop until the end of Cursor and add each entry to Ticks ArrayList.
do {
String businessName = cursor.getString(cursor.getColumnIndexOrThrow(RowBusinessName));
if (businessName != null) {
businessNameList.add(businessName);
}
} while (c.moveToNext());
}
return businessNameList;
}
These are work around.
The appropriate answer would be to create an Object that holds id and businessName. That way, you build an object from DB and just return the entire Object.

return ArrayList<String> with specific record from SQLiteDataBase

I want to get values but the function always returns null. Even though I debug and there is value inside variable rv.
This is my method:
public ArrayList<String> getList(int id) {
try {
ArrayList<String> rv = new ArrayList<String>();
open();
Cursor c = db.rawQuery("select * from reviews where IDRE="+id, null);
if(c.moveToFirst() || c.getColumnCount()==1) {
rv.add(String.valueOf(c.getInt(c.getColumnIndex("IDRE"))));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("ID_FK"))));
rv.add(c.getString(c.getColumnIndex("DATE")));
rv.add(c.getString(c.getColumnIndex("TYPE")));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("COST"))));
rv.add(c.getString(c.getColumnIndex("SERVICE")));
rv.add(c.getString(c.getColumnIndex("ATMOSPHERE")));
rv.add(c.getString(c.getColumnIndex("OVERALL")));
rv.add(c.getString(c.getColumnIndex("COMMENT")));
}
c.close();
close();
return rv;
}catch(Exception e) {
return null;
}
}
Some logging would help determine if you're throwing an error and ending up in that catch block, as #Daniel Nugent is saying.
But I think the issue is with your if expression. c.moveToFirst is going to move your cursor to the first row of your data source, and then return true unless that data source is empty, so the only time that if block does not occur is when your data source is empty. The only way c.getColumnCount()==1 is having any effect on the evaluation of your expression is if you have a table with only one column and no rows. Let us know what you're trying to achieve with that, and add some logging, and we'll be better able to help you.
I have edited your code ...and given two example , you can refer any one...
public ArrayList<String> getList(int id) {
try {
ArrayList<String> rv = new ArrayList<String>();
open();
Cursor c = db.rawQuery("select * from reviews where IDRE="+id, null);
if(c==null)
return null;
c.moveToFirst();
rv.add(String.valueOf(c.getInt(c.getColumnIndex("IDRE"))));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("ID_FK"))));
rv.add(c.getString(c.getColumnIndex("DATE")));
rv.add(c.getString(c.getColumnIndex("TYPE")));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("COST"))));
rv.add(c.getString(c.getColumnIndex("SERVICE")));
rv.add(c.getString(c.getColumnIndex("ATMOSPHERE")));
rv.add(c.getString(c.getColumnIndex("OVERALL")));
rv.add(c.getString(c.getColumnIndex("COMMENT")));
c.close();
close();
return rv;
}catch(Exception e) {
return null;
}
}
Second way:
public ArrayList<String> getList(int id) {
try {
ArrayList<String> rv = new ArrayList<String>();
open();
String[] columns=new String[]{"IDRE","ID_FK","DATE","TYPE","COST","SERVICE","ATMOSPHERE","OVERALL","COMMENT"};
Cursor c=sql_db.query("reviews", columns, "IDRE"+"=?", new String[] {String.valueOf(id)}, null, null, null);
if(c==null)
return null;
c.moveToFirst();
rv.add(String.valueOf(c.getInt(c.getColumnIndex("IDRE"))));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("ID_FK"))));
rv.add(c.getString(c.getColumnIndex("DATE")));
rv.add(c.getString(c.getColumnIndex("TYPE")));
rv.add(String.valueOf(c.getInt(c.getColumnIndex("COST"))));
rv.add(c.getString(c.getColumnIndex("SERVICE")));
rv.add(c.getString(c.getColumnIndex("ATMOSPHERE")));
rv.add(c.getString(c.getColumnIndex("OVERALL")));
rv.add(c.getString(c.getColumnIndex("COMMENT")));
c.close();
close();
return rv;
}catch(Exception e) {
return null;
}
}

How to retrieve a record from sqlite

Hi i'm new to android programming and i have created a sample app which allows the user to get data from the database. however its not displaying the data, it doesn't have any error message its just not displaying it. database is confirmed that there is data. please check my code maybe i forgot something here. thanks
public void onClick(View arg){
name = txtNameS.getText().toString();
if(arg.getId()==R.id.btnfortune){
searchRecord(count);
lblmessageS1.setText(name); // this is just for me to check if it will be displayed and it is.
lblmessageS2.setText(message);
}
}
public void searchRecord(int count) throws SQLException {
Cursor rsCursor;
String [] rsFields = {"mesNum","Message"};
rsCursor = dbM.dbase.query("MessageFile", rsFields, "mesNum = " + count, null, null, null, null, null);
rsCursor.moveToFirst();
if (rsCursor.isAfterLast()==false){
message = rsCursor.getString(1);
}
rsCursor.close();
}
by the way count is initialized as 1. and there are 10 records in the database. and there are 2 columns in the database the mesNum and Message, what i want is to display only the message column.
// SQLiteDatabase sqldb
Cursor rsCursor= sqldb.rawQuery("your query", null);
if (rsCursor!= null) {
if (rsCursor.moveToFirst()) {
do {
// do here for get data message = rsCursor.getString(1);
}while (cursor.moveToNext());
}
cursor.close();
}
add only one column name in your array
String [] rsFields = {"Message"};
cursor = dbM.dbase.query(true,"MessageFile", rsFields, "yourcolumn= "+count, null, null, null, null, null);
while( cursor != null && cursor.moveToNext() )
{
cursor.getString(0);
}
cursor.close();

Closing cursors across JAR boundaries

I use a content provider/resolver, have a separate project/lib that provides a number of DB helper methods. I have a second project/lib that does handy things with a cursor.
Imagine as such DB Helper Method (com.example.DBHelper):
public String[] dumpColumnTable() {
Cursor cursor = cr.query(MY_URI,
new String[] { FIELD },
null,
null,
null
);
return UtilMethods.createArrayFromCursor(cursor);
}
Then the Util methods (com.example.UtilMethods):
public static String[] createArrayFromCursor(Cursor cursor) {
return createArrayFromCursor(cursor, 0);
}
public static String[] createArrayFromCursor(Cursor cursor, int column) {
if (cursor == null) return null;
String[] strings = new String[cursor.getCount()];
if (cursor.moveToFirst()) {
int i=0;
do {
strings[i] = cursor.getString(column);
i++;
} while (cursor.moveToNext());
}
return strings;
}
Obviously the cursor isn't closed. This will leak a cursor. Logcat will give you that message.
SO, close it in the inner util function:
public static String[] createArrayFromCursor(Cursor cursor, int column) {
if (cursor == null) return null;
String[] strings = new String[cursor.getCount()];
if (cursor.moveToFirst()) {
int i=0;
do {
strings[i] = cursor.getString(column);
i++;
} while (cursor.moveToNext());
}
cursor.close();
return strings;
}
But logcat will still claim the cursor wasn't closed before finalize.
If instead, in the DB Helper method, I save the return value, close the cursor, then return it, I get no cursor leak/logcat message:
public String[] dumpColumnTable() {
Cursor cursor = cr.query(MY_URI,
new String[] { FIELD },
null,
null,
null
);
String[] toret = UtilMethods.createArrayFromCursor(cursor);
cursor.close();
return toret;
}
Why ? In debugging, the cursor is marked as close when the calls return. The call stack goes from my activity->db helper->util methods. The db helper and util methods are in separate projects from the activity.
Is there some pass by reference/value issue I'm missing, or crossing multiple JAR boundaries, or the casting of what is a SQLiteCursor to the generic Cursor type that I'm missing ?

Categories

Resources