Search code examples
androidadaptersimplecursoradapterlistadapter

How to use SimpleCursorAdapter with single_choice and multiple_choice


I am developing a quiz application which contain both multiple answer type and single answer type.the question and answer are store in sqlite database.i use simple cursor adapter and get idea about how to use from here! My question is that how i can switch from simple_list_item_single_choice to simple_list_item_multiple_choice if my answer type changes(single to multiple) and also how can i save the answer choosen.Please give some idea about it.Here is the coding....

  db = new DBAdapter(this);
  SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
  android.R.layout.simple_list_item_1, 
  db.getAllTitles(), 
  new String[] { "title" }, 
  new int[] { android.R.id.text1 });

 ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);

Solution

  • check this code: for single choice:

     SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
      android.R.layout.simple_list_item_single_choice, 
      db.getAllTitles(), 
      new String[] { "title" }, 
      new int[] { android.R.id.text1 });
    
     ListView listView = (ListView) findViewById(R.id.list);
     listView.setAdapter(adapter);
     listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    

    for multiple:

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
      simple_list_item_multiple_choice, 
      db.getAllTitles(), 
      new String[] { "title" }, 
      new int[] { android.R.id.text1 });
    
     ListView listView = (ListView) findViewById(R.id.list);
     listView.setAdapter(adapter);
     listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    

    depend on your requirement you have to set one of above: i think you aleady kno which question require single ans & which require multiple depend on that you have to also create list item click like

    listView.setOnItemClickListener(new OnItemClickListener() {
    
                private String my_sel_items;
    
                public void onItemClick(AdapterView arg0, View arg1, int arg2,
                        long arg3) {
                    if(ans == multiple){
                    my_sel_items = new String("Selected Items");
                    SparseBooleanArray a = lView.getCheckedItemPositions();
    
                    for (int i = 0; i < a.size(); i++) {
                        if (a.valueAt(i)) {
                            my_sel_items = my_sel_items + ","
                                    + (String) listView.getAdapter().getItem(i);
                        }
                    }
                    Log.v("values", my_sel_items);
                   }else{
                     // for single it default selected item
                   }
                }
            });