Abdelrahman Manna Abdelrahman Manna - 4 months ago 22
Android Question

Android Using alert Dialog with object

I am using an alert dialog that shows a menu on the beginning of the app, I want the dialog to show me 2 values which are "name"s from an object, here is the code of the alert dialog:

public void showDialog() {

EntityType en = new EntityType();
ArrayList array = ApplicationController.entities;

final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick one");
builder.setItems(array, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// I want to write my code here
}
});

builder.show();
}


en is my object that contain a string "name" and ApplicationController.entities contains the array

Answer
public void showDialog() {

    EntityType en = new EntityType();
    ArrayList array = ApplicationController.entities;

    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Pick one");
    ArrayList<String> displayValues=new ArrayList<>();
      for (Entity entity : array) {
         displayValues.add(entity.name);
      }

      ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,array);
      final AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setTitle("Pick one");
      builder.setSingleChoiceItems(displayValues, 0, new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialog, int which) {
            Entity selectedItem = array[which];
         }
      });    


    builder.show();
}
Comments