How to modify AlertDialog (Android)? - java

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();
}
}

Related

Visual customization of a dialog button

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();

How to show user input details back on alert dialog?

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();
}
});

Show popup once?

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.

Alert dialog not working correctly - android

I am using an alert dialog to ask the user for confirmation of an item addition to an array. I am printing the array size before and after the alert dialog and it seems that both printings are done before the alert dialog shows up.
Log.d("before", ""+wayPoints.length);
AlertDialog.Builder ab = new AlertDialog.Builder(getContext());
ab .setTitle("Add entry");
ab .setMessage("Are you sure you want to add this entry?");
ab .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{wayPoints = ArrayHandler.addAtIndex(wayPoints, node, 1);}
});
ab .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});
ab.setIcon(android.R.drawable.ic_dialog_alert);
ab.show();
Log.d("after", ""+wayPoints.length);
The ArrayHandler.addAtIndex method handles the addition of a new item to the provided array.
The problem is it is printing both logging lines before the alert dialog shows up. I need the alert dialog to be done before the printing of the second log.
This is correct behavior. The show method does not wait or block until the dialog is dismissed. Code execution continues after the show method immediately after the dialog is shown. (Actually, the dialog isn't even displayed yet - that happens after you yield control).
You already have setPositiveButton and setNegativeButton handlers, just put the code you want to execute in those handlers when user presses a button.
If you want certain code to run when the dialog is closed regardless of which button is tapped, use setOnDismissListener and put your code there.
Use:
AlertDialog alert1 = ab.create();
alert.show();
Instead of:
ab.show();
Try this
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( context);  
// set title
alertDialogBuilder.setTitle("Your Title");
  // set dialog message
alertDialogBuilder .setMessage("Click yes to exit!") .setCancelable(false) .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
MainActivity.this.finish(); }
}) .setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
wayPoints = ArrayHandler.addAtIndex(wayPoints, node, 1);
Log.d("after", ""+wayPoints.length);
} });
});  
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();  
// show it
alertDialog.show();

Beginner Button click event

I am new to Android, i am writing a program where when a user clicks a button a Alert Dialog to appear. This alert dialog has 2 buttons, Yes and No. Upon clicking Yes/No, i need to sysout the response.
The code i have so far; Can someone help me add the Alert Dialog;
public class HelloWorldProjectActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myFirstScreen);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==(R.id.button1)){
System.out.println("first button clicked");
// I need a Alert Dialog to appear here, and that will have 2 buttons YES and NO, the users response should be printed to the console.
}
}
You cannot System.out.print().
There are several methods to display the result. One is to use Toast. It will briefly show a text message and then disappear.
new AlertDialog.Builder(this)
.setMessage("Are you sure?")
.setPositiveButton("Yes", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(TestAndroidActivity.this, "YES CLICKED",
Toast.LENGTH_LONG).show();
}
}).setNegativeButton("No", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(TestAndroidActivity.this, "NO CLICKED",
Toast.LENGTH_LONG).show();
}
}).show();
Modify your code as follows:
The activity class doesn't have to implement OnClickListener.
Thus, remove onClick() method
Go to the layout file, add an attribute android:onClick="click" in the button declaration.
Add public void click(View view) with the previous code.
First of all, there really isn't any system.out to print to in android. What you should try instead is printing to the log. For information on how to print to the log, check this out. To then see the activity of the log (including messages you printed to it), checkout the logcat.
Second, for information on creating an alert dialog, please view this documentation.

Categories

Resources