EltMrx
EltMrx

Reputation: 37

How can I move from my last entry in a cursor to the first (and vice versa) using a Cursor and Sqlite DB?

I have a Sqlite DB that I'm accessing with a Cursor. I can scroll through the cursor and run my "check();" method. the issue I'm having is when I scroll past the cursor.

ie: hitting my previous button when on the first entry or hitting my next button when on the last entry...

I tried to put in an if statement to automatically move to the proper location.

What I'm trying to do is if I'm on the first position and hit the previous button I want to move to the last position in the cursor and continue.

Also if the cursor is in the last position and tries to scroll past that I'd like it to go to the first position. Below is my attempt at trying to make this happen.

@Override public void onClick(View v) {

    View src = v;
    switch (src.getId()) {
    case R.id.ButtonPrevious:       

        if  ((main.cursor.moveToPrevious()) ==  (main.cursor.moveToFirst()))
        {
            main.cursor.moveToLast();

        }else{
            main.cursor.moveToPrevious();   
        }                               
        check();



    case R.id.ButtonNext:


        if  ((main.cursor.moveToNext()) == (main.cursor.moveToLast()))
        {
            main.cursor.moveToFirst();

        }else{
        main.cursor.moveToNext();
        }
        check();
    }
}

Upvotes: 1

Views: 3622

Answers (1)

Steve Bergamini
Steve Bergamini

Reputation: 14600

You need to utilize the isAfterLast and isBeforeFirst methods of the Cursor class. Do something like this

case R.id.ButtonPrevious:
    cursor.moveToPrevious();
    if (cursor.isBeforeFirst()){
        cursor.moveToLast();
    }
    check();
case R.id.ButtonNext:
    cursor.moveToNext();
    if (cursor.isAfterLast()){
        cursor.moveToFirst();
    }
    check();

Not all the code, but the critical part. Hope that helps.

Upvotes: 4

Related Questions