I'm popping up an AlertDialog when a ListView item is clicked and the string of the message is very large (nearly 20,000 characters). What winds up happening is that I click the list item and it sits for about 3-4 seconds before displaying the AlertDialog. This is problematic for many reasons, primarily that the user could click the button repeatedly and crash the app.
My first thought was to try to mimic how the Google Play app handles their open source license display (Play -> Nav Drawer -> Settings -> Open Source License info), where they pop open the AlertDialog and then it looks as though the view/text is loaded after the dialog is shown. I imagined it looking something like this:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title);
builder.setMessage(veryLongStringMessage);
builder.setCancelable(true);
builder.setNeutralButton(android.R.string.ok, listener);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
Pretty basic stuff up until this point. Then I've tried to remove the message set in builder for something like:
builder.setMessage("")
// create/show dialog as above
alertDialog.setMessage(veryLongStringMessage);
But that seems to just load the whole dialog before showing it. So I thought maybe post a runnable to go at the end of the activity calls, and that wasn't working. I tried doing this in an Async task and could not get it working that way either. I've tried this as a DialogFragment where I call
activity.getSupportFragmentManager().executePendingTransactions();
Then go on to try to set the message after I know the DialogFragment has been shown and I either wind up with an empty dialog (the new message won't show up) or it loads it all at once and I'm sitting with that 3-4 second delay.
Anyone have any good method of implementing and AlertDialog with a very large message?
This case is when I show the legal notices of Google Play Services:
The problem seems to be the Dialog.show(), it takes those seconds in order to generate the layout.
So what I have done in my case, probably not the best one but it works. I create a temporal dialog.
private void showGPSLicense() {
AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MyActivity.this);
LicenseDialog.setTitle(getString(R.string.google_maps_legalnotices));
LicenseDialog.setMessage(getString(R.string.google_maps_loading));
final Dialog loadingDialog = LicenseDialog.create();
loadingDialog.show();
//This dialog does not take much time. Meanwhile I get via AsyncTask the heavy message, replacing/dismissing the previous dialog.
(new AsyncTask<Void, Void,AlertDialog.Builder>() {
#Override
protected AlertDialog.Builder doInBackground(Void... arg0) {
String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(getApplicationContext());
AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(MyActivity.this);
LicenseDialog.setTitle(getString(R.string.google_maps_legalnotices));
LicenseDialog.setMessage(LicenseInfo);
return LicenseDialog;
}
protected void onPostExecute(AlertDialog.Builder result) {
Dialog dialog = result.create();
dialog.setOnShowListener(new OnShowListener() {
public void onShow(DialogInterface dialog) {
loadingDialog.dismiss();
}
});
dialog.show();
}
}).execute();
}
Tested on Nexus 5 (4.4.2)
If you are worried about many clicks you can also prevent many clicks by implementing the OnClickListener:
public abstract class PreventManyClicksListener implements OnClickListener {
private boolean clickable = true;
public abstract void preventManyClicks(View view);
public final void onClick(View view) {
if (clickable) {
clickable = false;
preventManyClicks(view);
}
}
public void setClickable() {
clickable = true;
}
}
//...
private PreventManyClicksListener preventDialog = new PreventManyClicksListener() {
#Override
public void preventManyClicks(View view) {
showGPSLicense();
setClickable();
}
};
//..
myView.setOnClickListener(preventDialog);
I think you need to use a custom view in order to be able to do this, because you can't update an AlertDialog message after it's been created. Create a custom view with a TextView with an id of textView1 and ProgressBar with id of progressBar1 then create the following class.
public class MyDialogFragment extends DialogFragment {
private TextView mTextView;
private ProgressBar mProgressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_dialog, container, false);
mTextView = view.findViewById(R.id.textView1);
mTextView.setVisibility(View.GONE);
mProgressBar = view.findViewById(R.id.progressBar1);
mProgressBar.setVisibility(View.VISIBILE);
return view;
}
#Override
public View onStart() {
super.onStart();
mTextView.setText(getArguments().getString("text");
mProgressBar.setVisibility(View.GONE);
mTextView.setVisibility(View.VISIBILE);
}
}
You also need to pass it the text string in its arguments.
DialogFragment dialog = new MyDialogFragment();
Bundle args = new Bundle();
args.putString("text", text);
dialog.setArguments(args);
dialog.show(getFragmentManager(), "my_dialog")
Related
I think this has only started happening with recent Android API(s), but the problem is that the first time you try to select a checkbox in a MultiChoice Dialog, it requires an additional click for the UI to update.
I'm pretty sure it's due to an Android bug as my code is very simple.
After a lot of experimenting, I've found the answer so will share it below...
The tricky part of the solution was to get the View object. Once you have the View, you can invalidate() it in order to update the UI of the checkboxes.
Here is the essentials from my DialogFragment subclass:
public class MyMultiChoiceDialogFragment extends DialogFragment {
private View mView = null;
#Override #NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title);
builder.setMultiChoiceItems(
cursor,
isCheckedColumn
labelColumn
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which, boolean isChecked) {
// Handle the checkbox de/selection
/*
* The problem is that, despite onClick being called (with the correct parameter values), the
* checkbox ticks were not updating on the UI.
* Solution is to invalidate/redraw the layout so the checkboxes also update visually
*/
mView.invalidate();
mView.forceLayout(); // Following tests, this line is also required.
}
});
AlertDialog dialog = builder.create();
/*
* This seems to be the only way to get the view.
* Save it in an instance variable so we can access it within onClick()
*/
mView = dialog.getListView();
return dialog;
}
#Override
public void onDestroyView() {
super.onDestroyView();
mView = null; // Clean up / prevent memory leak - necessary?
}
}
I want to show a custom dialog box when I start my first activity without using a button. I try to search but I'm not finding the proper solution what I really want to do. Many of them are using onClick Listener to achieve that the scenario. Below image is showing an activity with a dialog box, that's what I'm looking for but without using onClick Listener.
How can we implement without using onClick Listener?
Any code contained in a click listener also works elsewhere in the class (unless you use the view that's clicked)
Create the dialog in onCreate. It will open immediately when the activity is started
In your main Activity oncreate method:
createCustomizeDialog();
now create this method outside of oncreate:
private void createCustomizeDialog() {
final AlertDialog.Builder builder=new AlertDialog.Builder(this);
LayoutInflater inflater = getActivity().getLayoutInflater();
#SuppressLint("InflateParams") final View alertLayout = inflater.inflate(R.layout.customize_dialog, null);
Button submit=(Button)alertLayout.findViewById(R.id.sButton);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
builder.setView(alertLayout);
alertDialog=builder.create();
//noinspection ConstantConditions
alertDialog.show();
}
Just try this way
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("TADAAAA!").create().show();
}
If you want to show the dialog only for the FIRST launch of this activity, you should put the code for your dialog in onCreate method of this activity, if it should be done for EVERY launch of this activity - then in onStart() method.
I'm building an Android application and that aplication have an open part and some actions that need authentication.
What I do is to when the user click on an action that needs authentication a login dialog is show, the user can login and the login will be valid for 30 minutes.
So I have 3 buttons in an fragment that when clicked check if the user is logged in, an if not calls a login dialog.
The problem is: How can I identify what button was clicked, because when the user click the button and is not authenticated I just create the login dialog and set the setTargetFragment to the caller fragment, that was the same for the 3 buttons.
Is there a way to pass a parameter to the login dialog to identify that?
The code are as following:
When the user click the button:
final DialogFragment loginDialog = new LoginDialogFragment();
loginDialog.setTargetFragment(this, 0);
btnAprovar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!LoginService.getInstance().isLoggedOn()) {
loginDialog.show(getFragmentManager(), "Login");
}
}
});
And In the dialog:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.fragment_login_dialog, null);
final EditText txtUser = (EditText) v.findViewById(R.id.txtUsername);
final EditText txtPwd = (EditText) v.findViewById(R.id.txtPassword);
builder.setView(v)
.setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
DoLogin dl = new DoLogin();
dl.execute(txtUser.getText().toString(), txtPwd.getText().toString());
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LoginDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
private void DoPost(Boolean _result) {
if (_result.equals(true)) {
((PublicacaoDetailFragment) this.getTargetFragment()).onAuthTrue();
} else {
((PublicacaoDetailFragment) this.getTargetFragment()).onAuthFalse();
}
}
What is the best Practice to do that?
Thanks
To extend #Rodolfo's answer, you should probably use the decorator/wrapper pattern here.
Instead of extending DialogFragment, in your LoginDialogFragment you should just have an instance variable of a DialogFragment. This way, you can have a method called show(String buttonDescription), for example. Inside your own show(...) method, you can call the show() method of the DialogFragment.
Since you are extending DialogFragment in a class of your own, you have two choices:
Define a variable (with getter and/or setter) inside your custom Dialog class. In your login button onClick method, before calling show() of your Dialog, call the setter for this variable and pass v.getId(). In this case, v is the View associated with the component that you've added the OnClickListener.
Pass your button View id within a Bundle to your DialogFragment.
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..
Could someone point out a working example of a custom dialog that takes an ArrayAdapter as input and shows a selectable list.
I have tried to create a Dialog using an AlertDialog Builder as such...
final ArrayAdapter<MyObject> myAdapter = getMyobjects();
final AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle("Pick an item").setAdapter(myAdapter,
new android.content.DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int item) {
Toast.makeText(Islands.this, myAdapter.getItem(item).toString(), Toast.LENGTH_SHORT).show();
}
});
final AlertDialog alert = builder.create();
return alert;
My problem is that my dialog is not updating then i called
#Override
protected void onPrepareDialog(final int id, final Dialog dialog) {
switch (id) {
case DIALOG_GET_AVAIL_DESTS:
((AlertDialog) dialog).getListView().setAdapter( getDestinations());
break;
}
}
However the onClick listener listens to the initial set of items...
Indeed AlertDialog is implements Facade design pattern with this class behind :
http://www.netmite.com/android/mydroid/frameworks/base/core/java/com/android/internal/app/AlertController.java
And the whole code is such a mess...
I took 3 hours to try to do that, and I am going to build a dialog from scratch, using android.R.layout as a basis.
Steff
You have to make a call to
invalidateViews()
on your listview - that will cause it to redraw the view with the updates.
Since you are using onPrepareDialog(int id, Dialog dialog), I am guessing you're initially setting up the dialog in onCreateDialog(int id).
Doing so cause the system to save the dialog you initially create. In order to achieve the desired functionality, when the dialog is dismissed, tell the system to discard it by calling android.app.Activity.removeDialog(int id).
Any subsequent invocations will have your dialog regenerated through the onCreateDialog(int id) method, causing the set of items to be updated.