Search code examples
androidsqlitecursorandroid-viewbinder

Displaying an icon in a database using ViewBinder


I have successfully created a table using SQlite in android. There is a column for sex( male/female) in the database. What I would like to do is to is to check the sex type and display a male/female icon depending on the type. I have used setViewBinder() which passes the column index(which column exactly i don't know ), but I believe we can use this to check the sex column. Is there a better way to do this?

        ListView lv=(ListView)findViewById(R.id.mylist);


         dbh = new DatabaseHelper(this);

           c = dbh.getReadableDatabase().rawQuery("SELECT _id, " + 
                   DatabaseHelper.NAME + 
           ", " + DatabaseHelper.LASTNAME + 
           ", " + DatabaseHelper.ans2 + ", " + DatabaseHelper.SEX + 
           " FROM " +
           DatabaseHelper.TABLE_NAME, null); // initializing 


  String[] dataFrom ={DatabaseHelper.NAME, DatabaseHelper.LASTNAME, DatabaseHelper.ans2, DatabaseHelper.SEX};
  int[] dataTo = {R.id.name, R.id.value1, R.id.value2, R.id.icon};

  SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
               R.layout.row, c, dataFrom, dataTo);
  adapter.setViewBinder(new ViewBinder(){


       public boolean setViewValue(View view, Cursor cursor,
               int columnIndex) {
           if (view.getId() == R.id.icon) {
               int sex = cursor.getInt(columnIndex);
               String s = String.valueOf(sex);
               if (s == "male") {
                   ((ImageView) view).setImageResource(R.drawable.male);
               } else if (s == "female"){
                   ((ImageView) view).setImageResource(R.drawable.female);
               }

               return true;    
           } else {
               return false;
           }

       }

   });
lv.setAdapter(adapter);

Solution

  • The method bindView allows you to set/check your data easily because you receive:

    • you cursor positioned to the actual position
    • the view in which you can place your data