onCreate() method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.database);
ListView lv=(ListView)findViewById(R.id.mylist);
dbh = new DatabaseHelper(this);
c = dbh.getReadableDatabase().rawQuery("SELECT _id, " +
DatabaseHelper.NAME +
", " + DatabaseHelper.LASTNAME +
", " + DatabaseHelper.ans2 +
" FROM " +
DatabaseHelper.TABLE_NAME, null); // initializing
String[] dataFrom ={DatabaseHelper.NAME, DatabaseHelper.LASTNAME, DatabaseHelper.ans2};
int[] dataTo = {R.id.name, R.id.value1, R.id.value2};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.row, c, dataFrom, dataTo);
lv.setAdapter(adapter);
registerForContextMenu(lv);
}
My row.xml file to display all data:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:layout_weight="30"
android:id="@+id/name"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="40"
android:gravity="center_horizontal"
android:id="@+id/value1"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="30"
android:gravity="right"
android:id="@+id/value2"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:src="@drawable/ic_launcher"
android:id="@+id/icon"
/>
</LinearLayout>
I have successfully created a table with SQLite. I would like to display an icon in each database row which will be displayed (using ListView) and the icon should depend on a certain element from the row. For example , if the sex (DatabaseHelper.SEX) is male, then we would display a male icon , and if the sex is female , we would display a female icon. If you look at my xml file , I have an icon already displayed ( which is the default android icon, but this is not what I want). Any ideas?
You could make you own adapter(extending
SimpleCursorAdapter) and override only thebindView()method and set the icon as you like:Use this adapter for your
ListViewand of course don’t forget to add to the query theDatabaseHelper.SEXcolumn:Edit:
Or you can use a
ViewBinder: