Lesson 63. Dialogues. AlertDialog. Single choice list

Lesson 63. Dialogues. AlertDialog. Single choice list

In this lesson:

– form a list with a single choice in the dialog

The lesson will be similar to the past, only now we will not update the dialog list data.

We will form a single-choice list in the dialog and determine which item has been selected (check).

Let’s create a project:

Project name: P0631_AlertDialogItemsSingle
Build Target: Android 2.3.3
Application name: AlertDialogItemsSingle
Package name: en.startandroid.develop.p0631alertdialogitemssingle
Create Activity: MainActivity

IN strings.xml write down the texts:


main.xml, Three buttons:


DB.java similar to the previous lesson, just remove the method of changing records

package ru.startandroid.develop.p0631alertdialogitemssingle;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DB {
  private static final String DB_NAME = "mydb";
  private static final int DB_VERSION = 1;
  private static final String DB_TABLE = "mytab";
  public static final String COLUMN_ID = "_id";
  public static final String COLUMN_TXT = "txt";
  private static final String DB_CREATE = 
    "create table " + DB_TABLE + "(" +
      COLUMN_ID + " integer primary key, " +
      COLUMN_TXT + " text" +
  private final Context mCtx;
  private DBHelper mDBHelper;
  private SQLiteDatabase mDB;
  public DB(Context ctx) {
    mCtx = ctx;
  // открыть подключение
  public void open() {
    mDBHelper = new DBHelper(mCtx, DB_NAME, null, DB_VERSION);
    mDB = mDBHelper.getWritableDatabase();
  // закрыть подключение
  public void close() {
    if (mDBHelper!=null) mDBHelper.close();
  // получить все данные из таблицы DB_TABLE
  public Cursor getAllData() {
    return mDB.query(DB_TABLE, null, null, null, null, null, null);
  // класс по созданию и управлению БД
  private class DBHelper extends SQLiteOpenHelper {

    public DBHelper(Context context, String name, CursorFactory factory,
        int version) {
      super(context, name, factory, version);

    // создаем и заполняем БД
    public void onCreate(SQLiteDatabase db) {
      ContentValues cv = new ContentValues();
      for (int i = 1; i < 5; i++) {
        cv.put(COLUMN_ID, i);
        cv.put(COLUMN_TXT, "sometext " + i);
        db.insert(DB_TABLE, null, cv);

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

MainActivity.java changed a bit:

package ru.startandroid.develop.p0631alertdialogitemssingle;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

  final String LOG_TAG = "myLogs";

  final int DIALOG_ITEMS = 1;
  final int DIALOG_ADAPTER = 2;
  final int DIALOG_CURSOR = 3;
  DB db;
  Cursor cursor;

  String data[] = { "one", "two", "three", "four" };

  /** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {

    // открываем подключение к БД
    db = new DB(this);
    cursor = db.getAllData();

  public void onclick(View v) {
    switch (v.getId()) {
    case R.id.btnItems:
    case R.id.btnAdapter:
    case R.id.btnCursor:

  protected Dialog onCreateDialog(int id) {
    AlertDialog.Builder adb = new AlertDialog.Builder(this);
    switch (id) {
    // массив
    case DIALOG_ITEMS:
      adb.setSingleChoiceItems(data, -1, myClickListener);
    // адаптер
      ArrayAdapter adapter = new ArrayAdapter(this,
          android.R.layout.select_dialog_singlechoice, data);
      adb.setSingleChoiceItems(adapter, -1, myClickListener);
    // курсор
      adb.setSingleChoiceItems(cursor, -1, DB.COLUMN_TXT, myClickListener);
    adb.setPositiveButton(R.string.ok, myClickListener);
    return adb.create();

  // обработчик нажатия на пункт списка диалога или кнопку
  OnClickListener myClickListener = new OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
      ListView lv = ((AlertDialog) dialog).getListView();
      if (which == Dialog.BUTTON_POSITIVE)
        // выводим в лог позицию выбранного элемента
        Log.d(LOG_TAG, "pos = " + lv.getCheckedItemPosition());
        // выводим в лог позицию нажатого элемента
        Log.d(LOG_TAG, "which = " + which);

  protected void onDestroy() {


IN onCreate we connect to the base.

onclick - depending on the button pressed, we call the appropriate dialog.

onCreateDialog - create a dialog called using AlertDialog.Builder. The dialog can construct a list using one of the following objects:

1) massif rows. The setSingleChoiceItems method is used. The input, the position of the selected element, and the click handler are fed to the input. If we pass -1 to the value of the selected element, there will be no selected element in the list.

2) adapter. We create an ArrayAdapter using the data array and the standard layout select_dialog_singlechoice, and pass it to the setSingleChoiceItems method. We also pass the position of the selected element and the handler there.

3) cursor DB. Call the setSingleChoiceItems method. We pass the cursor, the position of the selected element, the name of the field (the value of which will be displayed in the list) and the click handler.

In addition to the list, we specify only the title. Finally add the OK button, create and return the Dialog.

As you can see for all three methods of creation methods with the same name setSingleChoiceItems are used, but with different arguments for input.

myClickListener - Handler of clicking on the list items and the button. If there was a click on the button (which means closing the dialog), we will log information about the selected element. Otherwise (clicking on the list item) - we display the position of the clicked item. If the dialog contains a list of single or plural by selecting, then clicking on the list item does not close dialogue. But it can be implemented programmatically.

IN onDestroy close the connection to the database.

We'll save everything and run it. Let's call any dialogue.

Nothing was selected because we specified -1 in the setSingleChoiceItems method.

Click on the item, it stood out

And a text appeared in the beam

which = 2

Clicking OK will close the dialog. A log displays the position of the selected item.

pos = 2

If you open the dialog again, the selected item will remain selected. Because the dialogue is not destroyed at closing. If you want to change the selected item before each call, implement the method onPrepareDialog. In it it is necessary to get to the list and to call a method setItemChecked.

Example code that selects the third element (numbering from zero):

  protected void onPrepareDialog(int id, Dialog dialog) {
    ((AlertDialog) dialog).getListView().setItemChecked(2, true);

In the next lesson:

- form a list with multiple choices in the dialog

Discuss in the forum [29 replies]

Leave a Comment