thathashd
thathashd

Reputation: 1022

Populating a list view from SQLite Database

I'm new to android. What i'm trying to do is to populate a listview from my sqlite database.I know how to do it using arrays. Can somebody help me doing this? I know there is a away to adapt the following code and using it for populating the listview using SQLite but i don't know how to do it.

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_item);
        final ListView lt = (ListView)findViewById(R.id.ListView01);
        List<String> w= new ArrayList<String>();
        ArrayAdapter<String> aa;
        w.add("waka");
        w.add("weka");
        w.add("woka");
        aa = new ArrayAdapter<String>(this, R.layout.listW, w);
        lt.setAdapter(aa);
        lt.setTextFilterEnabled(true);
        lt.setOnItemClickListener(new OnItemClickListener() {     
            public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                  final String aux= (String) lt.getItemAtPosition(position);
                  Intent myIntent = new Intent(infoList.this, tabList.class);
                  startActivity(myIntent);
            }});
    }

Thanks

Upvotes: 2

Views: 7595

Answers (2)

Moss
Moss

Reputation: 6012

The best way to poputaling a ListView with data is using Content Providers: http://developer.android.com/guide/topics/providers/content-providers.html

Using content providers will you safe headaches regarding open/close operation for the database.

Upvotes: 2

Olegas
Olegas

Reputation: 10507

You can use SimpleCursorAdapter.

Image you have a list view (named 'list_item') item with two fields having ids txtOne and txtTwo respectively. Also, you are having a database table with tow fields - field1 and field2.

When you sgolud use the following adapter call.

SimpleCursorAdapter adapter = new SimpleCursorAdapter(
    ctx,
    R.layout.list_item,
    getContentResolver().query(....), // getting cursor for database query here.
    new String[] { "field1", "field2" },
    new int[] { R.id.txtOne, R.id.txtTwo }
);        

This adapter will map a text from field1 to txtOne and from field2 to txtTwo.

Upvotes: 2

Related Questions