Search code examples
javaandroidsqliteopenhelper

Getting ArrayList with SQLOpenHelper not working


I have a problem with my SQLiteOpenHelper class. I have a database with printer manufacturers and details of any kind of printer. I try to get all manufacturer from my database with this code and returning them in a arraylist.

// Read database for All printer manufacturers and return a list
public ArrayList<String> getPrManufacturer(){
    ArrayList<String> manufacturerList = new ArrayList<String>();
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.query(CoDeskContract.Printer.TABLE_NAME,
                             printerManuProjection, null, null, null, null, null,null);

    // If cursor is not null and manufacturer List 
    // does not contains Manufacturer in the list then add it!
    if ((cursor != null) && (cursor.getCount()>0)){
        cursor.moveToFirst();
        do {
            String cursorManufacturer = cursor.getString(0);
            //Checking for manufacturer in the list
            for(String manufacturerInList:manufacturerList){
                if (!manufacturerInList.equals(cursorManufacturer))
                    manufacturerList.add(cursorManufacturer);               
            }                   
        }while(cursor.moveToNext());
    }

    // Return list of manufacturers from database
    return manufacturerList;
}

I want every manufacturer to be once in a list. Somehow i cant to get it to work. Im still a newbie.

Thanks for any Help.


Solution

  • There are two issues:

    1. In the beginning, when your list manufacturerInList is empty then it will not go inside for(String manufacturerInList:manufacturerList){ loop and hence it will never add any entry in the list.

    2. Once you fix your problem 1, still it will not work as if (!manufacturerInList.equals(cursorManufacturer)) checks against each entry in the list and adds the non matching entry in the list possibly multiple times.

    To fix the issue, you have two options.

    Option1: Use contains as:

                if (!manufacturerList.contains(cursorManufacturer)) {
                     manufacturerList.add(cursorManufacturer); 
                }
    

    Option2: Use a matchFound boolean flag as:

            String cursorManufacturer = cursor.getString(0);
            boolean matchFound = false;
    
            //Checking for manufacturer in the list
            for(String manufacturerInList:manufacturerList){
                if (manufacturerInList.equals(cursorManufacturer)){
                     matchFound = true;
                     break;
                }
            }                   
            if(!matchFound){ // <- doesn't exit in the list
                manufacturerList.add(cursorManufacturer); 
            }