AlertDialog with a list shows empty dialog - android

In my Android app I have a dialog that supposed to show a list:
final AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
builder.setTitle("Pick a branch to navigate to:");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1);
adapter.addAll(branches);
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent searchAddress = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + branches.toArray()[which]));
startActivity(searchAddress);
}
});
builder.show();
When I launch this code, I get a dialog with the title, and blank space below, but when I click the blank space it does the action and uses what it got right, so something wrong with the view.
What can I do with that?

If your onClick actions doing fine it means that List filled properly only problem with showing views. So check out your adapter class.
EDIT:
Change Application Context to Activity's Context

Related

How to scroll custom list view in Alert Dialog programmatically?

I'm developing an Android app. Currently I've implemented custom list view in Alert Dialog. This is the code so far:
private void setupAlertDialogBuilder(final Context context) {
GiftStoreCountriesAdapter giftStoreCountriesAdapter = new GiftStoreCountriesAdapter(context,
R.layout.gift_store_countries_row,
giftStoreCountriesViewModel.fetchCountriesFromLocalDatabase(),
(HomeActivity) context);
builder = new AlertDialog.Builder(context)
.setIcon(R.drawable.ic_currency_icon)
.setAdapter(giftStoreCountriesAdapter, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handleCountrySelection(dialog, which);
}
});
builder.create().getListView().setFastScrollEnabled(true);
builder.create().getListView().smoothScrollToPosition(scrollToPosition(context));
}
Everything works fine except one thing. How can I programmatically scroll that custom list view to the some position or index of row as soon as alert dialog is shown to user. I've tried with this:
builder.create().getListView().setFastScrollEnabled(true);
builder.create().getListView().smoothScrollToPosition(scrollToPosition(context));
but it doesn't work. If I put just:
getListView().smoothScrollToPosition(scrollToPosition(context));
without builder.create() I get NullPointerException. This is in class that is custom Alert Dialog and it extends AlertDialog. I need to automatically scroll this list when it's shown to user. I appreciate all your help.

Dialog error when open from a Adapter + ListView

I have a little problem with a Dialog.
It's a ListView of Videos with thumbnails that load the videos with an Adapter. The ListView register an OnItemClickListener and inside the OnClickItem method I try to raise the Dialog.
I've tried with various types of Dialog but nothing happened. A simplified piece of code it's here:
public class ListOfVideos extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_of_videos);
init_phone_video_grid();
}
private void init_phone_video_grid() {
// Here's some code for the video reading
// The ListView
videolist = (ListView) findViewById(R.id.PhoneVideoList);
videolist.setAdapter(new VideoAdapter(getApplicationContext()));
videolist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Here's some code for the video reading
/** ============= Here's the problem ================ **/
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setMessage("Example Message")
.setTitle("This is the title!!")
.setCancelable(false)
.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
System.out.println("[debug]" + "Open File " + filename);
}
});
}
The list of videos load perfectly. But when I click on an Item:
The Dialog does not show
I got a error message in the LogCat, that state: "show() Dialog's window is null!"
The println debug message, appears ok in the LogCat
I have searched for that message error, but there's not much information.
I think the problem could be on the Context that receive the Builder, but I'm stuck on this point.
Any advice will be apreciated
That error message is saying that the Context given to the AlertDialog.Builder has no attached window, which Dialogs need as a UI anchor, basically. An Activity is what should be used for such a Context, as it will have the required window.
Without seeing VideoAdapter's code, the root cause is presumably new VideoAdapter(getApplicationContext()), which is handing your VideoAdapter the application Context to build Views with. That likely means that the v passed into onItemClick() is one such View, and v.getContext() is returning that application Context in new AlertDialog.Builder(v.getContext()).
That application Context does not have a window but your Activity does, as mentioned. Furthermore, the Activity is actually what you want to give to VideoAdapter to build Views with anyway, to ensure that they are created with the correct theme and styling. Change that relevant line to:
videolist.setAdapter(new VideoAdapter(ListOfVideos.this));
That alone might solve the issue, depending on what VideoAdapter does internally. However, it's arguably better to specify the Activity again in the AlertDialog.Builder constructor call, just so there's no question:
AlertDialog.Builder builder = new AlertDialog.Builder(ListOfVideos.this);
As a final note, whenever a Context is needed for any UI component, you usually want to use the immediately available Activity.
Here is a example of How to create dialog box..
String message = "Hello";
AlertDialog.Builder alt_bld = new AlertDialog.Builder(
CurrentActi.this);
alt_bld.setTitle("Alert")
.setMessage(message)
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//here right the code that you want perform onClick
dialog.cancel();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
alert.setTitle("Alert");
alert.show();
May be it will help you..

Android Listview dialog doesn't disapear after choosing an item

I've tried to create a list view dialog to display a list of choose. My code is shown below:
LayoutInflater factory=LayoutInflater.from(this);
final View stuckLevelDialogView=factory.inflate(R.layout.report_stuck_dialog, null);
final ListView stuckLevelListViewForDialog=(ListView)stuckLevelDialogView.findViewById(R.id.report_stuck_dialog_listview);
final String[] stuckLevelList=new String[]{"1 - You can move freely","2 - You have to be aware of your movement","3 - You can move slowly","4 - There is a traffic jam","5 - There is a serious traffic jam"};
ArrayAdapter<String> adapterForDialog=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, stuckLevelList);
stuckLevelListViewForDialog.setAdapter(adapterForDialog);
final AlertDialog.Builder stuckLevelDialog=new AlertDialog.Builder(this);
stuckLevelDialog.setTitle("What stuck level is this point?");
stuckLevelDialog.setView(stuckLevelDialogView);
stuckLevelDialog.show();
However, when I choose an option, the onItemClick is executed, but the listview dialog doesn't disappear, I have to press back button manually. I've tried to debug the code for a whole day, but it has not been solved yet. Please help me. Thank in advanced!
I think you need to dismiss() the dialog in your onItemClick listener as below:
stuckLevelListViewForDialog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> p_arg0, View p_arg1,
int p_arg2, long p_arg3) {
stuckLevelDialog.dismiss();
}
});
Use stuckLevelDialog.dismiss; at the end of onItemClick.
You can set setSingleChoiceItems in your alert dialog box with your items list, which will show a list with a radio buttons. If you want to add buttons you can else once user select any items you can dismiss the dialog.
new AlertDialog.Builder(this)
.setSingleChoiceItems(array, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// here you can do your functionality and can dismiss dialog as well
dialog.dismiss();
}
})
.show();

How to display an arraylist in AlertDialog

i'm trying to get an arraylist on alert dialog but i can see the list items only if i click them. any idea whats wrong with the below code .any suggestions pls....
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final ArrayAdapter<String> aa1=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_single_choice, matches);
builder.setSingleChoiceItems(aa1, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
numbers.add(aa1.getItem(item));
aa.notifyDataSetChanged();
dialog.dismiss();
}
});
alert = builder.create();
alert.show();
I believe this is caused by a bug when using the default themes and AlertDialog.Builder.
You should be able to work around it by copying the android.R.layout.simple_list_item_single_choice layout xml out of the platform and creating a local layout file with the android:textColor properties overridden to something other than themed text color attributes.
Just use this one
android.R.layout.simple_spinner_dropdown_item
simple dialog here try this. Just you have to pass string or charsequence array to it shows simple dialog..

Android: onItemClick only returns first selected Item

I'm using and ArrayAdapter to populate a ListView. After selecting and item, it displays a confirmation Y/N dialog. If the user's choice is negative, then he should be able to select another item showing the same dialog. And so on.
Here's my code:
lView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent, final View v, final int index, final long id) {
Toast.makeText("Selected file"+ mFiles.get(index).getfileName(),
Toast.LENGTH_SHORT).show();
SelectedFile = mFiles.get(index);
showDialog(DIALOG_CONFIRMIMPORT_ID);
}
});
The weird thing is that while the "Toast" shows the clicked item every time, only the first selected item since the Activity is initiated is being passed to "SelectedFile". No matter how many times you click a diferent item, "SelectedFile" always assumes the same value, the value of the first clicked item, outside of this code.
Heres's my Dialog code:
Protected Dialog onCreateDialog(int id) {
switch(id) {
case DIALOG_CONFIRMIMPORT_ID:
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String message = String.format(getString(R.string.importstudentfileconfirm),SelectedFile.getfileName());
builder.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Activity.this.finish();
// startActivity(new Intent(Activity.this, LOL.class));
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SelectedFile = null;
dismissDialog(DIALOG_CONFIRMIMPORT_ID);
mFiles.notifyAll();
}
});
AlertDialog alert = builder.create();
return alert;
}
}
return null;
}
Thank you very much for any help!
I'm guessing this has something to do with the fact that the onCreateDialog method is only called the first time the dialog is created. So the first time you see the dialog it will have the correct filename.
After onCreateDialog is called, onPrepareDialog(...) is called. onPrepareDialog, allows you to change the dialog after it has been created, but before it gets displayed.
Remember that underneath everything, Android isn't creating a new Dialog for you every time you want to show the DIALOG_CONFIRMIMPORT_ID dialog. It is too computationally expensive to instantiate a new dialog every time. Instead, it creates it once, which causes onCreatDialog to be called, followed by the onPrepareDialog. Every other time the dialog is shown, it only calls onPrepareDialog.
Check out the following article on the Android Developer site. It explains things pretty clearly.
http://developer.android.com/guide/topics/ui/dialogs.html#ShowingADialog
So try using onCreateDialog just for initialization of stuff that won't change between showings of the dialog, then use the onPrepareDialog method to dynamically update the contents of the dialog (i.e. getting the new filename)
Cheers!

Categories

Resources