a line is drown over alertDialog.setButton in MainActivity.java - android

I am doing alert dialog demo. It work fine but I found a line over "setButton" in MainActivity.java file. Hear is my code:
#SuppressWarnings("deprecation")
public void onClick(View arg0) {
// Creating alert Dialog with one Button
AlertDialog alertDialog = new AlertDialog.Builder(
MainActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Welcome to AndroidHive.info");
// Setting Icon to Dialog
// I got line hear........ over setButtob .........
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Write your code here to execute after dialog
// closed
Toast.makeText(getApplicationContext(),
"You clicked on OK", Toast.LENGTH_SHORT)
.show();
}
});
// Showing Alert Message
alertDialog.show();![enter image description here][1]
}
});`
You cab see the image here and get more idea of what I mean to say.

You mean you got a warning saying the method is deprecated?
That's because setButton is not used anymore, it's deprecated, instead you should be doing something like this:
alertDialog.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// blablabla
}
});
Also notice you can get the String "OK" like thing as well : android.R.string.ok , which is the recommended way ;)

I went through the url image, which made your question clear. This is showing because that method( setButton) is depreciated. You are using
#SuppressWarnings("deprecation")
at the top. This prevents is from giving the warning message and you cannot read the warning message( which probably is that: This method has been depreciated). If you remove the top line, then it will tell you why it shows cross line over setButton. See here. It says that this method was depreciated in API level 3.
For seeing how use use it in proper way, you can go through this official documentation page of using Alert Dialog. You can also see the tutorial here.

Related

Android: How to make AlertDialog disappear on clicking ok button?

I am asking the same question which is asked before at below links but the solution proposed in these links is not working for me so I am posting it again.
How to make an AlertDialog disappear?
Android AlertDialog always exits when I click on OK Button
How to navigate to next activity after user clicks on AlertDialog OK button?
Basically, I am creating an AlertDialog builder to notify the user for asking to enable a setting for the Usage Data Access and when the OK button is pressed then the Settings menu gets opened. When I press back button to come back on the app then the AlertDialog is still available there although I expected to be dismissed to be back on my app.
public void show_alert(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("This application requires access to the Usage Stats Service. Please " +
"ensure that this is enabled in settings, then press the back button to continue ");
builder.setCancelable(true);
builder.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
dialog.dismiss();
}
});
builder.show();
return;
}
Any hint what wrong could be going here?
Edit after some testing:
I tested OPs code on 6.0.1 and it behaved as expected - i.e. the dialog was dismissed after clicked 'OK'. I'll leave my initial answer below as an alternative that also works. Additional alternatives can be found here.
You can get a reference to your Alert Dialog it from your builder.show() method:
mMyDialog = builder.show();
In your onClick method:
mMyDialog.dismiss();
Full sample:
AlertDialog mMyDialog; // declare AlertDialog
public void show_alert(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("This application requires access to the Usage Stats Service. Please " +
"ensure that this is enabled in settings, then press the back button to continue ");
builder.setCancelable(true);
builder.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
mMyDialog.dismiss(); // dismiss AlertDialog
}
});
mMyDialog = builder.show(); // assign AlertDialog
return;
}

Android alert dialog good usage

I couldn't find anything usefull on the internet about my problem. So my question is how do you do a good usage of Android's alert dialogs. Here is an example of code creating and showing an alert dialog just with the title "error", the text "you can't do that" and a "Ok" button :
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Error");
alertDialogBuilder.setMessage("You can't do that");
alertDialogBuilder.setCancelable(true);
alertDialogBuilder.setPositiveButton(
getResources().getString("ok"),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
alertDialogError = alertDialogBuilder.create();
alertDialogError.show();
But now, if I have many of this alert dialogs in my application, what should I do ?
Should I set the alertDialogBuilder as an attribute so each time I want to display an error message I can call his function setMessage() and then create() and then show() ?
Should I keep an already configured alertDialog for every single error message I have so I can just call theRightAlertDialog.show() to display my message ?
Something else ?
What's the good usage/cleanest way to do this for you ?
You could do this one of two ways. The first is to create a static method, which you can place in a final utility class:
public final class AlertUtil {
public static void showErrorDialog(Context context, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Error");
builder.setMessage(message);
builder.setCancelable(true);
builder.setPositiveButton(
getResources().getString("ok"),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
}
}
Or you can use a DialogFragment which you can create with:
getSupportFragmentManager().beginTransaction().add(ErrorDialogFragment.newInstance(message), "tag").commit()`
I will say though, as a side note; if you are looking to change more than just a few fields for each of the dialogs (i.e. adding more parameters to the showErrorDialog method), then you probably should just stick to the Builder pattern. Considering that is what the Builder pattern is meant for.
Should I set the alertDialogBuilder as an attribute so each time I want to display an error message I can call his function setMessage() and then create() and then show() ?
If the title and the button functionality are the same for all of your alerts, than this would be the best strategy. Create a variable for the alertDialogBuilder, or even just the alertDialog itself, then change the message and show it each time.
Alternatively, you could create a method that builds the dialog, and takes in a string for the message text.

How exactly to act on a confirmation dialog?

New to Android... I understand Dialogs are asynchronous. But I really can't get my head around the flow for confirming an action. Can someone please explain the flow?
I want to save a file on the sdcard. The Activity prompts the used for the filename. Then it checks to see if the file exists. If it exists, it needs to prompt the user to confirm if they want to overwrite it. Then it proceeds to erase and write the file.
I know you can't hold execution waiting for the response. How then would this common flow work in Android?
Thanks
I am not 100% it is what you are looking for, but here is a link to the Android documentation explaining how we should display Confirmation and Acknowledgement popups using the "Android standard way":
http://developer.android.com/design/patterns/confirming-acknowledging.html
I do not know the exact flow, I suppose it would depend on how the application was written. I would check for the file if it existed call the dialog windows then if the Ok/Yes/Confirm is pressed overwrite the file.
Dialogs | Android Developers - Has an excellent code example
public class FireMissilesDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_fire_missiles)
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES! AKA Overwrite your file.
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog AKA do nothing
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
I know it's slightly silly example but basically check for the file (if exist) > Call Dialog (if yes)> Overwrite.

Why arent my log messages showing up?

I have some code that build a dialog box and makes a listener for it. The dialog box displays fine, but the code inside the listener doesn't seem to run, and I don't know why.
private void showBackgrounDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MeacruxActivity.this);
builder.setTitle(R.string.background_dialog_title).setCancelable(true)
.setItems(R.array.background_options,
new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int selection) {
Log.d(logID, "the selection is: " + selection);
if(backgrounds.length==selection){
notImplementedYet.show();
return;
}
setBckground(backgrounds[selection]);
}
});
currentDialog = builder.create();
currentDialog.show();
}
private void setBackground(String bgName) {
Log.d(logID, bgName);
}
The dialog shows up properly with all the options and everything, but when I click on one nothing come sup in the log.... Why is that?
Edit: I did some more testing and I can confirm that the code inside of the onClick function is being run, its just that the log isnt showing up...
I'm assuming you are looking in eclipse or studio
In DDMS view, make sure the device is selected.
In Logcat view, make sure there's not a filter applied.
On terminal, type adb logcat... does it show up there?

How can we pass any value (selected one) from dialog to activity in android?

I need help to pass values from a custom dialog to an activity.
I cannot understand what should i use. I already used intent, but dialog doesn't support intent value passing .
So anyone can help me here, i am totally stucked.If you have any basic example for it, then that will be excellent.
Thank You.
Snippet from the Google Documentation:
// Alert Dialog code (mostly copied from the Android docs
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
myFunction(item);
}
});
AlertDialog alert = builder.create();
// Now elsewhere in your Activity class, you would have this function
private void myFunction(int result){
// Now the data has been "returned" (as pointed out, that's not
// the right terminology)
}

Categories

Resources