I have two buttons. One for previous and one for next sqlite database record.
Here is how i am trying to get the next record from the database.
public long getNext(int id,DataBaseHelper helper){
Story story = new Story();
Cursor cursor = story.getStories(helper, 0);
//Updated code
cursor.moveToPosition(id);
cursor.moveToNext();
return cursor.getLong(1);
//Updated code
}
The problem is that if the previous position i pass it is "1", the next position i get is "3". Why does it skip one record? It keeps on skipping one record every time. Please tell me if i'm doing something wrong since i'm new at this and i have looked everywhere but this specific issues seems to be happening to me.
UPDATE : Code edited to show a better approach(perhaps)
Remember that Cursor.getPosition() starts to count from 0. So, the first record is at index #0, the second one at index #1, ...
Take a look at the official documentation : Cursor.moveToPosition(int position)
Let take a look at your code :
(id = 1, for the example)
cursor.moveToPosition(id);
// Cursor is now on the record #1, so the second one of the list
cursor.moveToNext();
// Cursor is now on the record id+1 = #2, so the third one of the list
return cursor.getLong(1);
// Returns the value of the colon #1 of the third record
// of the list : so the record at the index #2
Ok. I have been a little wrong with the approach here. I was ignoring the fact that the cursor index starts from -1 and that the database index of my table starts from 1. So i had to subtract -1 from the id variable and it solved the problem :) Here is the code that worked for me.
public long getNext(int id,DataBaseHelper helper){
id = id - 1;
Story story = new Story();
Cursor cursor = story.getStories(helper, 0);
//Updated code
cursor.moveToPosition(id);
cursor.moveToNext();
return cursor.getLong(1);
//Updated code
}
Related
I have some pretty big DBObjects of which I want to store basic information in an array. I count them, initialize the array in the correct size and then fill it with their basic information. Right now, the count method gives back 5, but there are 6 objects and the iteration finds them all.
public DBObject[] allDbObjects() {
long count = dbc.coll.count();
System.out.println(count + " results found");
DBObject[] results = new DBObject[(int) count];
int i=0;
DBCursor cursor = dbc.coll.find();
for (DBObject o: cursor) {
System.out.println("Found one project:");
results[i] = new BasicDBObject();
System.out.println(o.get("name"));
results[i].put("name", o.get("name"));
results[i].put("id", o.get("_id"));
results[i].put("description", o.get("description"));
i++;
}
return results;
}
Obviously, this gives me an ArrayIndexOutOfBoundsException for the last object. It tries to access results[5], which doesn't exist.
This has worked fine before and according to the mongodb docs, the find method works with the cursor. So basically the cursor thinks it has 5 objects first and then it gives me 6.
Where did I go wrong?
UPDATE: I changed this one to an ArrayList and it works, but I do the same thing at another place. That one worked just fine yesterday. Today it doesn't, I get the same error as I did in the code above.
so I've build a method that return an ArrayList of a class that I use on my project, the problem is that the only item that is being add to the ArrayList is the 2nd on the database. I know that because I extracted the DB File and browsed it, and also the 'c.getCount()' return a value of 2.
So I know for a fact that my DB includes 2 entries, my Cursor gets 2 entries... but for some reason he chooses to focus on the 2nd row at the beginning after I created it - and thus exiting the while loop, even thought I called c.moveToFirst();
Maybe I'm just tired and not seeng clearly what am I doing wrong... because I compared it to other methods in my code that works fine and I cannot tell the difference between them.
My method looks like this:
public ArrayList<Kiosk> getKiosks () {
ArrayList<Kiosk> kioskArrayList = new ArrayList<>();
db = dbHandler.getWritableDatabase();
String[] columns = {Tags.TAG_LOCAL_ID, Tags.TAG_ID_SERVER, Tags.TAG_NAME,
Tags.TAG_PHONE_NUMBER, Tags.TAG_CONTACT_NAME, Tags.TAG_SCHOOL_ID};
Cursor c = db.query(DatabaseHandler.TABLE_KIOSK, columns, null, null, null, null, null);
c.moveToFirst();
Log.i("tagg", "Size of the cursor is: " + c.getCount());
while (c.moveToNext()) {
Kiosk kiosk = new Kiosk();
kiosk.setLOCAL_ID(c.getInt(c.getColumnIndex(Tags.TAG_LOCAL_ID)));
kiosk.setIdServer(c.getInt(c.getColumnIndex(Tags.TAG_ID_SERVER)));
kiosk.setName(c.getString(c.getColumnIndex(Tags.TAG_NAME)));
kiosk.setPhoneNumber(c.getString(c.getColumnIndex(Tags.TAG_PHONE_NUMBER)));
kiosk.setContactName(c.getString(c.getColumnIndex(Tags.TAG_CONTACT_NAME)));
kiosk.setSchoolId(c.getInt(c.getColumnIndex(Tags.TAG_SCHOOL_ID)));
c.moveToNext();
kioskArrayList.add(kiosk);
Log.w("taggg", "Added this to the kiosk Array: " + kiosk.getName() +
"Local ID: " + kiosk.getLOCAL_ID());
}
Log.w("tagg", "getKioskhere, size of the array I sent is: " + kioskArrayList.size());
c.close();
db.close();
return kioskArrayList;
}
My log gives clearly says the cursor's size is 2 but the ArrayList is 1:
03-11 14:18:37.334: W/(18369): School id of the client is: 1
03-11 14:18:37.336: I/(18369): Size of the cursor is: 2
03-11 14:18:37.336: W/(18369): Added this to the kiosk Array: PitaKioskLocal ID: 2
03-11 14:18:37.336: W/(18369): getKioskhere, size of the array I sent is: 1
Any advice? thanks in advance
You first move to the first element:
c.moveToFirst();
Then you move to the second one, before you even processed the first one:
while (c.moveToNext()) {
Finally, you call
c.moveToNext();
within your while loop, which leads to ignoring every second entry.
Solution: remove the call within the loop, and process the first element before moving on to the second one. The easiest method would be to change while(){} to do{} while().
Set the sort order for the query. You also do a moveToNext() prior to any work.
Cursor c = db.query(DatabaseHandler.TABLE_KIOSK, columns, null, null, null, null, Tags.TAG_LOCAL_ID + " desc");
// stuff
do {
// Iterate over cursor
} while (c.moveToNext());
It looks like you are calling moveToNext() too many times.
You start at the first row with your call moveToFirst(). Then, as you enter your while loop, moveToNext() is called again. Thus, as you enter your loop you are already sitting on the second row. Then, inside the loop, you call moveToNext() and add your kiosk too the kioskArrayList.
When you hit the top of the while loop the second time, you are sitting at an index of 2, so c.moveToNext() evaluates to false, so you only add to the list once.
I'm creating an app which stores diary entries. Upon retrieving the diary entry I get a CursorIndexOutOfBoundsException, I believe it is something to do with my SELECT statement to get the information within the DB.
getDAO = new DAO(this);
Cursor showDiaryEntries = getDAO.queryDiary(Diary.DiaryItem.FULL_PROJECTION, Diary.DiaryItem.COLUMN_NAME_DIARY_TITLE+" = "+fieldTitle, null);
Long fieldDate = showDiaryEntries.getLong(1);
Long fieldTime = showDiaryEntries.getLong(2);
String fieldEntry = showDiaryEntries.getString(3);
mDate.setText(String.valueOf(fieldDate));
Log.i(TAG,"Field Date "+ fieldDate);
mTime.setText(String.valueOf(fieldTime));
Log.i(TAG,"Field Time "+ fieldTime);
mEntry.setText(fieldEntry);
Log.i(TAG,"Field Entry "+ fieldEntry);
I've been reading about this type of exception and believe it may be to do with when I getting the String/Long as I don't have a loop? Although I don't fully comprehend this.
Log Cat
03-07 07:10:59.475: E/AndroidRuntime(1471): FATAL EXCEPTION: main
03-07 07:10:59.475: E/AndroidRuntime(1471): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.democo.mydiary/com.democo.mydiary.DiaryEntryActivity}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
I was hoping someone would be able to educate me as to what the problem is.
Thanks
Make sure you call:
showDiaryEntries.moveToFirst();
Do this before you start doing anything to the cursor. This will make sure the cursor starts at the FIRST row in the database!
first make sure your cursor is
*not null
*Then move it to first position
if(showDiaryEntries!=null && showDiaryEntries.moveToFirst())
{
//Now do waht ever u want to do with cursor
}
Above code will take care of problem you are facing now and also which you may face in future.
When you fill a cursor, it is positioned BEFORE the first record (which index is 0); now your cursor index is -1, which corresponds to no record position.
Therefore you get an error (You try to get the values from the columns of no row).
This s why you should always moveToFirst your cursor before starting to use it.
Following code is to used for how to get cursor value.
Cursor showDiaryEntries= dbh.database_function();
if (showDiaryEntries.getCount() != 0 && showDiaryEntries!=null) {
if (showDiaryEntries.moveToFirst()) {
do {
fieldEntry = showDiaryEntries.getString(showDiaryEntries.getColumnIndex("database feild name here"));
} while (showDiaryEntries.moveToNext());
}
}
i am providing string for an example. so update your function with your long and string field..
For example:
public void removeStaleMovies(Set<String> updatedMovieList) {
Cursor cur = this.getReadableDatabase().rawQuery("SELECT id, title, year FROM movie", null);
cur.moveToFirst();
while (!cur.isAfterLast()) {
String title = cur.getString(1);
String year = cur.getString(2);
if (!updatedMovieList.contains(title + "-" + year)) {
// delete the row where 'id' = cur.getString(0)
// OR, delete the row using the object at the cursor's current position, if that's possible
// OR, if deletion isn't safe while iterating, build up a list of row id's and run a DELETE statement after iteration is finished
}
}
}
Is deletion safe to do? Or can it result in some unpredictable behavior? I am aware of this similar question, but I'm still unsure.
From a code safety standpoint, this should be OK, assuming that the result set of your query is less than 1MB. In that case, the Cursor holds in heap space the entire result set, so it is insulated from any changes to the underlying database.
That being said, you may want to build up a list of rows to delete, simply so you can delete them in a single statement, rather than a bunch of individual statements (though wrapping those individual statements in a transaction may give you similar performance characteristics).
i have a problem with a cursor. i created a alarm manager that pick a value to compare with another in looping.
My problem is this: if the cursor is outside of the loop this pick only my first value (if exsist only one value pick only this obviously).... if the cursor is in the loop, this pick only last value (if exsist only one value pick only this obviously).
how to fix this?
my query:
public Cursor getRegistry2()
{
return (getReadableDatabase().query(
TabRegistry.TABLE_NAME,
TabRegistry.COLUMNS,
TabRegistry._ID,
null,
null,
null,
null));
my cursor in service:
Cursor c5 = databaseHelper.getRegistry2();
c5.moveToFirst();
while(c5.isAfterLast() == false){
tipe = c5.getString(c5.getColumnIndex(TabRegistry.TYPE));
status = c5.getString(c5.getColumnIndex(TabRegistry.STATUS));
number = c5.getString(c5.getColumnIndex(TabRegistry.NUMBER));
c5.moveToNext();
}
c5.close();
thanks in advance!
As I mentioned in my comment, if you are actually trying to find a particular item you need to actually look for it.
Assuming you are looking to compare the status, you might do this:
while(c5.isAfterLast() == false){
tipe = c5.getString(c5.getColumnIndex(TabRegistry.TYPE));
status = c5.getString(c5.getColumnIndex(TabRegistry.STATUS));
number = c5.getString(c5.getColumnIndex(TabRegistry.NUMBER));
if (status.equals(comparisonString)){
break;
}
c5.moveToNext();
}
This would break out of your loop, leaving your values set for the item you were looking for.
Personally, that's a lot of computing overhead and I'd just make the query to look for the comparison value directly and then check and see if the returned cursor was empty. Much simpler.
I don't understand your problem but something that is strange for me is : while(c5.isAfterLast() == false){
Have you tried to replace by while (c5.moveToNext()) { and removing c5.moveToFirst(); ?
You should know that you are overwriting the values of tipe, status and number in case your cursor has values more than one.
Cursor c5 = databaseHelper.getRegistry2();
if(c5.moveToFirst()){
do{
tipe = c5.getString(c5.getColumnIndex(TabRegistry.TYPE));
status = c5.getString(c5.getColumnIndex(TabRegistry.STATUS));
number = c5.getString(c5.getColumnIndex(TabRegistry.NUMBER));
}while(c5.moveToNext());
}
c5.close();