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..
Related
I need to reload an activity from another activity in android application. That 2nd activity is a dialog window, and based on the dialog window base activity should refresh the contents. (By click button of dialog activity)
Reload your activity.
context.startActivity(context.getIntent());
context.finish();
Consider A is an activity you want to reload and B is another activity.
In this case, just call finish()
when you are moving from A to B. When you call A from B it will load the activity A again.
Dialog Window and activity is completely deferent things.
It is possible to refresh First Activity from it's dialog. You can do it using interface.
Here is simple solution. In your First Activity implements a Interface name IRefreshInteface. It's definition is like bellow:
public interface IRefreshInteface(){
public void doRefreshValue(String commandValue);
}
Now if you implement IRefreshInteface in your activity you will get method doRefreshValue(String commandValue) and write refresh code here.
#Override
void doRefreshValue(String commandValue){
// Write refresh code here
}
Now in your dialog you have Context of your Activity. Using that context object you can call this doRefreshValue(String commandValue) method easily. Here is the sample code :
public AlertDialog displayMessage(Context context, String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
LayoutInflater inflater = LayoutInflater.from(context);
final View v = inflater.inflate(R.layout.custom_view, null);
builder.setView(v);
shipText = (EditText)v.findViewById(R.id.shipNameEditText);
scientistNameText = (EditText)v.findViewById(R.id.scientistEditText);
scientistEmailText = (EditText)v.findViewById(R.id.emailEditText);
volumeText = (EditText)v.findViewById(R.id.volumeEditText);
colourText = (EditText)v.findViewById(R.id.colourEditText);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((IRefreshInteface) context).doRefreshValue("YOUR_COMMAND");
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog= builder.create();
dialog.show();
Button tb = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
tb.setOnClickListener(new CustomListener(dialog));
return dialog;
}
here, pass Context of Activity todisplayMessage() method and call activity method doRefreshValue using this way:
((IRefreshInteface) context).doRefreshValue("YOUR_COMMAND");
For more info visit here and here
Hope this will solve your problem. Sorry for bad english :)
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.
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
LogCat is telling me that my Application is unable to display a window, since "token null is not for an application". This is the code it's having problems with:
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setMessage("Er du sikker?\n" + taskList.get(position) +"\nvil starte med det samme hvis du trykker 'Ja'");
.setPositiveButton("Ja", dialogClickListener);
.setNegativeButton("Nej", dialogClickListener);
.show();
Ignore the Danish, that's just for our users. It's on .show() it starts acting up and throws FATAL. I looked this same issue up all over StackOverflow and found that it's likely a problem in getApplicationContext(), but I've been unable to figure out how to get the context of use otherwise.
I'll leave some of the code it's supposed to be used on here in case you need it.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { //give our listView an onItemClickListener
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { //when you click on an item
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { //it should open a dialog but doesn't
#Override
public void onClick(DialogInterface dialog, int which) { //if you click
switch (which){ //"ja"
case DialogInterface.BUTTON_POSITIVE:
Intent i = new Intent(getApplicationContext(), PlayScreen.class); //start a new intent to open PlayScreen
i.putExtra("task", taskList.get(position)); //with the task out of the ArrayList that was clicked
startActivity(i);
break;
case DialogInterface.BUTTON_NEGATIVE: //nothing
break;
}
}
};
Basically I think the problem is I don't know how to provide builder with the context it needs. It may have something to do with me being new to Android development.
Replace getApplicationContext() with this, assuming that this is an Activity. Activity inherits from Context, and you need to use an Activity to show a Dialog.
I am an idiot.
Basically I forgot I was using it in the context of a ListView, meaning I was attempting to use it with an activity. I got the context from the listview..
lv.getContext()
Sorry for wasting your time, if only I had spent 5 more minutes figuring out my position in the code...
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!