Jochen Birkle
Jochen Birkle

Reputation: 335

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?

Upvotes: 0

Views: 60

Answers (1)

Laviniux
Laviniux

Reputation: 364

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!

Upvotes: 1

Related Questions