Skip to content Skip to sidebar Skip to footer

Problem - Populate Database Into Listview In Android

hi all i need to populate database elements in listview. i get null pointer exception and array adapter errors. i did the following ways: 1)created a string array with size of num

Solution 1:

Try using the SQLiteOpenHelper to create a datahelper

implement a function like so:

publicList<List<String>> getData(){
       Cursor cursor = this.db.query(TABLE_NAME,newString[] { "value1", "value2" }, null, null, null, null, "code asc");
       List<List<String>> list = newArrayList<List<String>>();
       if (cursor.moveToFirst()){
           do{
               List<String> temp = newArrayList<String>();
               temp.add(cursor.getString(0));
               temp.add(cursor.getString(1));
               list.add(temp);
           }while (cursor.moveToNext());
       }
       return list;
   }

then in the other class call:

privateList<List<String>> liItems;
liItems = dh.getData();

/** create an array in the proper length */String[] rgItems = newString[liItems.size()];

/** Fill the array with data */for (int i=0; i < liItems.size(); i++){
        List<String> temp = liItems.get(i);
        rgItems[i] = temp.get(0) + " - " + temp.get(1);
    }
    /** Populate ListView with list */
    ArrayList<String> customerList = new ArrayList<String>();
    customerList.addAll( Arrays.asList(rgItems) );
    adItemAdapter = new ArrayAdapter<String>(this, R.layout.itemlisttext, rgItems);
    lvItemListview.setAdapter(adItemAdapter);

itemlisttext is a xmlLayout with textview

This works fine for me, hope it helps you.

Solution 2:

Well you have used counter to count record. use cursor.getCount();

And use SimpleCursorAdapter instead of ArrayAdapter. It will facilitate you.

Have a look at this Answer

Post a Comment for "Problem - Populate Database Into Listview In Android"