I am trying to show a popup, and if the user clicks dont show again, I want to never show it again. However, the dont show again button is not working. I am using shared preferences:
if (dialogPrefs.getBoolean("Show", true) == true) {
new AlertDialog.Builder(this)
.setTitle("Blah")
.setMessage("Blah blah blah ")
.setNegativeButton("Not now", null)
.setNeutralButton("Don't show again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialogEditor = dialogPrefs.edit();
dialogEditor.putBoolean("Show", false);
dialogEditor.commit();
}
})
.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
enable();
}
}).show();
My preferences and editor are declared in the beginning as such:
SharedPreferences dialogPrefs;
SharedPreferences.Editor dialogEditor;
The shared prefs are initialized in onCreate().
Please let me know what the problem may be.
Thanks,
Ruchir
Your problem is the declaration of the SharedPreferences; it is all declared but...not initialized! Where should the os write your key-value data?
I suggest you to read this Get a Handle to a SharedPreferences
Try this code, I tested it and work:
SharedPreferences dialogPrefs = this.getPreferences(Context.MODE_PRIVATE);
final SharedPreferences.Editor dialogEditor = dialogPrefs.edit();
if (dialogPrefs.getBoolean("Show", true)) {
new AlertDialog.Builder(this)
.setTitle("Blah")
.setMessage("Blah blah blah ")
.setNegativeButton("Not now", null)
.setNeutralButton("Don't show again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialogEditor.putBoolean("Show", false);
dialogEditor.commit();
}
})
.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.i("TAG", "onClick: enable");
}
}).show();
}
}
It should be like this:
if (!dialogPrefs.getBoolean("Show", false)) {//don't show again will work
instead of:
if (dialogPrefs.getBoolean("Show", true) == true) {//this will always show dialog
SharedPreferences.Editor.commit() returns a boolean, indicating the status of write to the actual SharedPreferences object. See if commit() returned true. Also, make sure, you're not editing the same SharedPreference using two Editors. The last editor to commit, will have its changes reflected.
Update Your code works fine, when I run it. I don't see anything wrong in your code. Please make sure you're writing to and reading from the same SharedPreferences.
Related
I am using a dialog in my app that pops up and interacts with the user. I haven't worked with dialogs before, so i know next to nothing about styling them. This is the code:
public void openDialog() {
#SuppressLint("InflateParams") View view = (LayoutInflater.from(AudioRecorder.this)).inflate(R.layout.audio_name_input, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(AudioRecorder.this);
alertBuilder.setView(view);
final EditText userInput = view.findViewById(R.id.userInput);
alertBuilder.setCancelable(true);
alertBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
inputName = String.valueOf(userInput.getText());
if (!inputName.isEmpty()) {
Toast.makeText(AudioRecorder.this, "Next audio clip will be named... " + inputName, Toast.LENGTH_SHORT).show();
filePathMaking();
} else {
inputName = "recorded_audio";
Toast.makeText(AudioRecorder.this, "Input field empty, next audio clip will be named... " + inputName, Toast.LENGTH_SHORT).show();
}
}
});
alertBuilder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
Dialog dialog = alertBuilder.create();
dialog.show();
}
Can we style the "Save" button to display red text?
You can get the Button and then change it's text color. Something along the following lines should work,
public void openDialog() {
#SuppressLint("InflateParams") View view = (LayoutInflater.from(AudioRecorder.this)).inflate(R.layout.audio_name_input, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(AudioRecorder.this);
alertBuilder.setView(view);
final EditText userInput = view.findViewById(R.id.userInput);
alertBuilder.setCancelable(true);
alertBuilder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
inputName = String.valueOf(userInput.getText());
if (!inputName.isEmpty()) {
Toast.makeText(AudioRecorder.this, "Next audio clip will be named... " + inputName, Toast.LENGTH_SHORT).show();
filePathMaking();
} else {
inputName = "recorded_audio";
Toast.makeText(AudioRecorder.this, "Input field empty, next audio clip will be named... " + inputName, Toast.LENGTH_SHORT).show();
}
}
});
alertBuilder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
Dialog dialog = alertBuilder.create();
dialog.show();
Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setTextColor(Color.parseColor("#FF0B8B42"));
}
You can use AlertDialog as Chrisvin Jem suggested in his answer but I would like to offer another solution:
You can just create a custom dialog class in order to give your dialog a custom layout, control everything in a separate class - I find it cleaner and more organized.
For example, create dialogClass:
public class ProgressDialog extends Dialog {
public ProgressDialog(#NonNull Context context) {
super(context);
setContentView(R.layout.progress_dialog); //this is your layout for the dialog
}
}
And all you need to do is to create dialog instant and call it like this:
ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.show(); // this line shows your dialog
Why I recommend using this and not AlertDialog.Builder :
You can build your layout in a faster way with custom dialog.
No need to write a lot of code just to add views when you can have a custom layout.
It's easier (or so I believe) for you to see myCoolDialog.show(); rather than 50 lines of code or more in a single method.
Do you need to change anything regarding your dialog look and code? good, go to your separate class and change it instead of adding 20 more code lines to your activity.
Chrisvin Jem gave the extact answer to your question however if you want more control over your design you can the this code
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.yourview);
RelativeLayout submit = dialog.findViewById(R.id.submit);
final EditText edittext = dialog.findViewById(R.id.edittext);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Toast.makeText(context, getString(R.string.thanks), Toast.LENGTH_SHORT).show();
}
});
dialog.show();
Please, i would like to show back details after the user must have input something, back on alert dialog box in Android studio. I used this code below:
editText = (EditText) findViewById(R.id.my_edit_txt);
editText.getText().toString();
But it doesn't show on the confirmation dialog box I created.
It looks like you didn't set the text of your AlertDialog, but this is just an assumption because there is not enough code in your question. Calling editText.getText().toString() does not do anything but return a String. It does not assign it to anything. An example with an AlertDialog would be the following:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(editText.getText().toString());
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Set other dialog properties
...
// Create the AlertDialog
AlertDialog dialog = builder.create();
I've took this example from Android Developers and modified it so that it includes the text of your EditText. This code should work because you not only call the toString() method but also assign it's return value to the AlertDialog's message property.
This is my entire code for the alert dialog box:
public void alertdialog(View view){
mybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder cfmalt = new AlertDialog.Builder(Dashboard.this);
//cfmalt.setMessage("Do you want to quit?").setCancelable(false);
//editText.getText().toString();
cfmalt.setMessage(editText.getText().toString()+"\n"+ vol_edit2.getText().toString());
cfmalt.setMessage(dt.getMonth())
//cfmalt.setMessage("Name:").setMessage(vol_edit2.getText().toString());
cfmalt.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
cfmalt.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
I'm a beginner for Java as well as for Android Studio so, here my problem is: I had created a alert dialog window for an activity with positive button being "OK" and negative button being "No thanks". As shown in the code below.
if(Times==0) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setIcon(android.R.drawable.ic_dialog_alert);
builder1.setTitle("Warning");
builder1.setMessage("Rooting of a phone may void your Warranty in most of the cases,so it is adviced to proceed at your own risk");
builder1.setCancelable(true);
builder1.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Times += 1;
dialog.cancel();
}
});
builder1.setNegativeButton(
"No Thanks",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
}
It was going fine but now the catch is I want it to be displayed only once if the user clicks the "OK" button and don't want to show it again if the user clicked "OK". I had created a variable times in my class and initialised it to zero as shown below.
public class rootingRooting extends AppCompatActivity {
int Times=0;
and put the complete AlertDialog in the if loop and incremented it's value when the user clicked "OK" so that the loop may execute only once if the user clicked "OK", but it is of no use whenever I open the activity the alert box is being displayed inspite of clicking "OK". So, now the things i want to do happen is:
The alert box should not be displayed if the user once clicked "OK".
If the user clicked the "no Thanks" button, I want to take him to the home activity. So, how should I use the intent with the "no thanks" button?
Thank you.
You need to use SharedPreferenes to save data persistently, local variables will not help.
something like this:
EDIT As per your request, I have added a sample activity class to show the whole process. See the comments in between for more info
EDIT 2 See the code after //Second Edit comment
public class MainActivity extends AppCompatActivity {
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//When the activity starts, we look into the shared prefs and get an int of name "ok_clicked" from it.
//0 will be the default value of the int if there is no int stored in sharedPreferences.
prefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
int times = prefs.getInt("ok_clicked", 0);
//if the times value is 0, we will open the dialog, otherwise nothing happens
if (times==0){
openDialog();
}
}
//Read This comment First: We will create a Method, which create an alert Dialog.
private void openDialog(){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Test").setMessage("Lorem ipsum dolor");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//When OK button is clicked, an int with value of 1 will be saved in sharedPreferences.
prefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("ok_clicked", 1);
editor.apply();
}
});
dialog.setNegativeButton("No Thanks", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Second Edit: To open another acitivty on No Thanks Button
Intent intent = new Intent(MyActivity.this, HomeActivity.class);
startActivity(intent);
}
});
dialog.show();
}
}
I'm new to Java/ Android development (I started learning last night) so it is entirely possible I'm doing something horrendously stupid. However, after more than an hour Googling I've come up with nothing. I'm using Eclipse as my editor.
I'm reading the docs here for AlertDialog, which gives an example:
public static class MyAlertDialogFragment extends DialogFragment {
public static MyAlertDialogFragment newInstance(int title) {
MyAlertDialogFragment frag = new MyAlertDialogFragment();
Bundle args = new Bundle();
args.putInt("title", title);
frag.setArguments(args);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(title)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
((FragmentAlertDialog)getActivity()).doPositiveClick();
}
}
)
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
((FragmentAlertDialog)getActivity()).doNegativeClick();
}
}
)
.create();
}
}
I originally re-wrote it so I can start committing some of the methods to memory, but got an error "FragmentAlertDialog cannot be resolved to a type". I hit Ctrl+Shift+O to make sure I had the proper imports, but still it didn't go away.
So I copied/ pasted the example code and did the following, in this order:
Hit Ctrl+Shift+O to get the imports right (using android.app.DialogFragment, not android.support.v4.app.DialogFragment)
Declared my package at the top
Replaced R.string.alert_dialog_ok and R.string.alert_dialog_cancel with android.R.string.ok and android.R.string.cancel respectively
Removed setIcon(), as I don't have an icon to put in yet
I'm still getting errors:
FragmentAlertDialog cannot be resolved to a type (x4)
Illegal modifier for the class MyAlertDialogFragment; only public, abstract & final are permitted
Am I doing something wrong, or is there something wrong with the example code?
1.FragmentAlertDialog
Make sure the Activity you want to cast to is named FragmentAlertDialog. Make sure to also save everything - sometimes Eclipse won't make the connection until everything is saved.
2.Illegal modifier for the class MyAlertDialogFragment; only public, abstract & final are permitted
Take out the static modifier:
public class MyAlertDialogFragment extends DialogFragment {
or keep static and move this Fragment so it is enclosed within the Activity you want. This means that MyAlertDialogFragment should be inside your Activity, before that Activity's closing brace.
I'm new to Java/Android development
Don't start off with something so complicated. Learn Java then move to Android.
Hi try these code to implement alert dialog
AlertDialog.Builder alert2 = new AlertDialog.Builder(this);
alert2.setTitle("Your Title");
alert2.setMessage("Your Messages");
final EditText input2 = new EditText(this);
input2.setInputType(InputType.TYPE_CLASS_PHONE);
alert2.setView(input2);
alert2.setPositiveButton(GButton, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do something with value!
try
{
// do your stuff here
}
catch(Exception e)
{
}
}
});
alert2.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert2.show();
Idea taken from Android: Blurring and dimming background windows from dialog. I'm having trouble getting the content under my dialog to blur. When calling eula.getWindow() I receive this error:
The method getWindow() is undefined for the type AlertDialog.Builder
The eula is displayed with this bit of code from the main activity:
EulaHelper.showEula(false, this);
Any help is greatly appreciated.
public static void showEula(final boolean accepted, final FragmentActivity activity) {
AlertDialog.Builder eula = new AlertDialog.Builder(activity)
.setTitle(R.string.eula_title)
.setIcon(android.R.drawable.ic_dialog_info)
.setMessage(activity.getString(R.raw.eula))
.setCancelable(accepted);
if (accepted) {
// If they've accepted the EULA allow, show an OK to dismiss.
eula.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
} else {
// If they haven't accepted the EULA allow, show accept/decline buttons and exit on
// decline.
eula
.setPositiveButton(R.string.accept,
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setAcceptedEula(activity);
dialog.dismiss();
}
})
.setNegativeButton(R.string.decline,
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
activity.finish();
}
});
}
eula.show();
WindowManager.LayoutParams lp = eula.getWindow().getAttributes();
lp.dimAmount = 0.0F;
eula.getWindow().setAttributes(lp);
eula.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
}
getWindow() is a method of the dialog class, not of the dialog builder. Your code should rather look like this:
AlertDialog dlg = eula.show();
WindowManager.LayoutParams lp = dlg.getWindow().getAttributes();
lp.dimAmount = 0.0F;
dlg.getWindow().setAttributes(lp);
dlg.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
Note though that the FLAG_BLUR_BEHIND constant is deprecated now, blurring behind windows is no longer supported. So your code might break in the future.
eula is the Builder, not the dialog itself. Try:
final AlertDialog eulaDialog = eula.create();
eulaDialog.show();
WindowManager.LayoutParams lp = eulaDialog.getWindow().getAttributes();
lp.dimAmount = 0.0F;
eulaDialog.getWindow().setAttributes(lp);
eulaDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);