Skip to content Skip to sidebar Skip to footer

SQLite To ListView(androidhive's Version)

I am trying to insert data from SQLite to a listview. I have tried look for example codes but they do not work. The database part is from AndroidHive's SQL tutorial. In his post th

Solution 1:

to get data from SQLite you can try like this:

      public List<String[]> selectAll()
{

    List<String[]> list = new ArrayList<String[]>();
    Cursor cursor = db.query(TABLE_NAME, new String[] { "id","name","number","skypeId","address" },
            null, null, null, null, "name asc"); 

    int x=0;
    if (cursor.moveToFirst()) {
        do {
            String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4)};

            list.add(b1);

            x=x+1;
        } while (cursor.moveToNext());
    }
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    } 
    cursor.close();

    return list;
}

and to show it in a list view :

    List<String[]> list = new ArrayList<String[]>();
List<String[]> names2 =null ;
     names2 = dm.selectAll();

    stg1=new String[names2.size()]; 

    int x=0;
    String stg;

    for (String[] name : names2) {
        stg = name[1]+" - "+name[2]+ " - "+name[3]+" - "+name[4];

        stg1[x]=stg;
        x++;
    }


    ArrayAdapter<String> adapter = new ArrayAdapter<String>(   
            this,android.R.layout.simple_list_item_1,   
            stg1);
    this.setListAdapter(adapter);
}      

refer this tutorial you will get an idea: http://www.vogella.com/articles/AndroidSQLite/article.html


Solution 2:

you will need to create an Database class instance in your Activity or ListActivity to access getAllCart as

public class TempActivity extends Activity {
DatabaseHandler db;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        db = new DatabaseHandler(TempActivity.this);

        // Reading all Carts
        List<Cart> Carts = db.getAllCart(); //<< get all Cart details here    
       //... your code here..  

and for showing Carts ArrayList values in ListView you will need to create an Custom Adapter for Adding all items in ListView rows .

for Create ListView with Custom Adapter you can view these tutorials :

Customizing Android ListView Items with Custom ArrayAdapter

Android ListView example


Post a Comment for "SQLite To ListView(androidhive's Version)"