Android creating AlertDialog using values from ArrayList?
Asked Answered
G

2

7

I am using following code to create a Dialog aleart box with lists item from studentNames ArrayList.I am creating this ArrayList by reading childfile array.But when this code runs it just display a Dialog box with zero list item.I have even check my studentNames for null but it has values in it.According to documentation I need to set ListAdapter for showing list items in Dialog box , but that's also not working for me.Please help me finding the problem.

ArrayList<String> studentNames  = new ArrayList<String>();
            for (File file2 : childfile) {
                studentNames.add(file2.getName());
            }

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(student.getName()).setAdapter(new ArrayAdapter(context, android.R.layout.simple_list_item_1, studentNames),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            switch (which) {

                               cases
                            }

                        }
                    });
            builder.create();
            builder.show();
Ghetto answered 17/10, 2012 at 14:43 Comment(1)
You forgot setItemsPokelogan
T
31

This is how you can achieve it:

final CharSequence[] items = {"1", "2", "3"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select");
builder.setItems(items, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
        // Do something with the selection
        dialog.dismiss();
    }
});
builder.show();
Tendance answered 17/10, 2012 at 15:24 Comment(2)
I wanted to use adapter and i don't have a predefined array itemsGhetto
CharSequence[] cs = studentNames.toArray(new CharSequence[list.size()]); this is what you can use for thatTendance
C
1

I have the solution for your question. So, I can see that you are populating the ArrayList studentNames with some data. Try the following code, in order to display the list in the DialogBox.

ArrayList<String> studentNames=new ArrayList<String>();

for(File file2:childfile){

        studentNames.add(file2.getName());

}
AlertDialog.Builder builder=new AlertDialog.Builder(context);
        builder.setTitle(studentNames.toArray
        (new String[studentNames.size()]),
        new DialogInterface.OnClickListener(){

//studentName.toArray() converts the List into Array so that you can use it as Dialog List.     

        public void onClick(DialogInterface dialog,intwhich){
            switch(which){

            //cases...

            }
        }

        });
}
builder.create();
builder.show();
Conchoidal answered 22/8, 2017 at 11:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.