user3091102
user3091102

Reputation: 15

How to return data from AlertDialog list in EditText

I have a clickable EditText and when I click on the EditText a dialog box opens. The dialog box has a list which is populated from data that are saved in databaseHelper class.

When the user selects an item from the dialog box, the dialog box should close and the selected data should be inserted in the EditText.

AlertDialog ad;
EditText selectdata;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.Main_layout);
     final DBHelper db = new DBHelper(this);

    selectdata = (EditText) findViewById(R.id.tfselectcategory);


    selectdata.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            showDialog();
        }
    }); 


}

private void showDialog(){
    DBHelper db = new DBHelper(getApplicationContext());

    final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle("Choose Category");

    // Spinner Drop down elements
    List<String> lables = db.sniperdata();
 // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_dropdown_item_1line, lables);
    dialog.setAdapter(dataAdapter, null);
    AlertDialog d = dialog.create();
    d.show();


}

Upvotes: 0

Views: 371

Answers (2)

ELITE
ELITE

Reputation: 5940

You have to code for OnClickListener of dialog interface.

private void showDialog(){
    DBHelper db = new DBHelper(getApplicationContext());

    final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle("Choose Category");

    // Spinner Drop down elements
    final List<String> lables = db.sniperdata();
 // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_dropdown_item_1line, lables);
    dialog.setAdapter(dataAdapter, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int ind) {
            selectdata.setText(lables.get(ind));
        }
    });
    AlertDialog d = dialog.create();
    d.show();
}

try this.

Upvotes: 1

Ravi
Ravi

Reputation: 35569

set clickListner for dialog listitem

dialog.setAdapter(dataAdapter,new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int item) {
           // write your code for dialog dismiss.
           Log.e("selected item=",lables.get(item));
   }
});

Upvotes: 2

Related Questions