mardi 13 janvier 2015

Android: Populate a a ListView from a Database

I have a SQLite Database that I want to use to populate a ListView, but I can't for the life of me figure out how to do that. Based on various internet sources (other questions/tutorials/etc.), I've been able to get this code, but it's clearly not working, as I'm now not even able to open the app in the emulator:


populateListView method



public void populateListView() {
Cursor cursor = db.getAllContacts();
String[] fromFieldNames = new String[] {DBAdapter.KEY_ROWID, DBAdapter.KEY_LOCATION, DBAdapter.KEY_TIME};
int[] toViewIds = new int[] {R.id.textView3, R.id.textView2, R.id.textView4};
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this,
R.layout.list_view_layout, cursor, fromFieldNames, toViewIds, 0);

ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(myCursorAdapter);
}


activity_main.xml



<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical"
android:id="@+id/TableLayout">


<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Set New Alarm"
android:id="@+id/setAlarmButton"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="onClickSetAlarm" />

<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView" />

</RelativeLayout>


list_view_layout.xml



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/textView2" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/textView3" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/textView4"
android:layout_gravity="center_horizontal" />
</LinearLayout>


I'm fairly certain that the issue isn't with the code for the DBAdapter, as it was working fine before I added this bit of code (I had it display a Toast with the data).


Thanks!


Aucun commentaire:

Enregistrer un commentaire