I create my AlertDialog on Android with the content I need:

 new AlertDialog.Builder(this) .setTitle(...) .setView(R.layout.layout_settings) // вот моя Layout .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface i1, int i3) { ... return; } }) .setNegativeButton("cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface i1, int i3) { ... return; } }) .create() .show(); 

In this my Layout R.layout.layout_settings there is a ListView :

 <ListView android:id="@+id/myListView" android:layout_width="match_parent" android:layout_height="wrap_content" /> 

How to add a String[] array with values ​​to it? Here without all these R.layout.simple_list_item_1 as written here . Does not work! An exception is thrown:

java.lang.NullPointerException:

Attempt to invoke virtual method 'void android.widget.ListView.setAdapter (android.widget.ListAdapter)' on a null object reference

I need to simply and elementarily point my ListView an ordinary String[] array. With these I will not express "simple_list_item .." easier to shoot.

I am not going to create any additional XML files (for example, Layout) for some unimportant ListView . Need another option.

  • one
    which line in Exception? android.R.layout.simple_list_item_1 does not require you to create any XML, it takes a standard element. - Nikotin N
  • Exception in the line myListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new String[]{...}); Sorry, forgot to specify it in the question. - nick
  • and how do you get the object myListView? - Nikotin N
  • one
    Well, most likely, therefore, NullPointer, because you need to look for a ListView on the dialog, i.e. dialog.findViewById - Nikotin N
  • 2
    Do you get a listView that is in the dialog before adding the dialog? think he won't be null? in debug mode, stop at setAdapter line and see what myListView - Nikotin N

1 answer 1

 AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); // ...Irrelevant code for customizing the buttons and title LayoutInflater inflater = this.getLayoutInflater(); View dialogView = inflater.inflate(R.layout.abc, null); dialogBuilder.setView(dialogView); dialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); dialogBuilder.setNegativeButton( "cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); ListView myListView = (ListView) dialogView.findViewById(R.id.lv); //добавляешь адаптер myListView.setAdapter(adapter); AlertDialog alertDialog = dialogBuilder.create(); alertDialog.show(); 
  • and what is myDialog on the seventh line? .. - nick
  • @ L'Esperanza, extra line. Works? - Nikotin N
  • Score 5. Great! . Thank. - nick