populating a list view with sql database items

大憨熊 提交于 2019-12-04 19:02:46

Create a function getAllCategory() in CategoryDatabase class.

public List<String> getAllCategory() {
    List<String> List = new ArrayList<String>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + DATABASE_TABLE;
    Cursor cursor = ourDatabase.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            List.add(cursor.getString(1));
        } while (cursor.moveToNext());
    }
    return List;
   }  

To populate items to listview.

In your MainActivity say on button click.

CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
            entry.open();
            List<String> all = entry.getAllCategory();
            lv = (ListView)findViewById(R.id.listView1);
            arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all);
            lv.setAdapter(arrayAdapter);

Edit :

In onCreate

    CategoryDatabase entry = new CategoryDatabase(MainActivity.this);
            entry.open();
            List<String> all = entry.getAllCategory();
                if(all.size()>0) // check if list contains items.
                {    
            lv = (ListView)findViewById(R.id.listView1);
            arrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, all);
            lv.setAdapter(arrayAdapter);
                }  
                else
                {
                   Toast.makeText(MainActivity.this,"No items to display",1000).show();
                } 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!