How can I implement a Preference that displays a simple yes/no confirmation dialog?
For an example, see Browser->Setting->Clear Cache.
That is a simple alert dialog, Federico gave you a site where you can look things up.
Here is a short example of how an alert dialog can be built.
new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Do you really want to whatever?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(MainActivity.this, "Yaay", Toast.LENGTH_SHORT).show();
}})
.setNegativeButton(android.R.string.no, null).show();
Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.
Unfortunately, it is in the com.android.internal.preference package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).
Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).
You can then add it to your preferences.xml like any other Preference. Example:
<com.example.myapp.YesNoPreference
android:dialogMessage="Are you sure you want to revert all settings to their default values?"
android:key="com.example.myapp.pref_reset_settings_key"
android:summary="Revert all settings to their default values."
android:title="Reset Settings" />
Which looks like this:
Use Intent Preference if you are using preference xml screen or you if you are using you custom screen then the code would be like below
intentClearCookies = getPreferenceManager().createPreferenceScreen(this);
Intent clearcookies = new Intent(PopupPostPref.this, ClearCookies.class);
intentClearCookies.setIntent(clearcookies);
intentClearCookies.setTitle(R.string.ClearCookies);
intentClearCookies.setEnabled(true);
launchPrefCat.addPreference(intentClearCookies);
And then Create Activity Class somewhat like below, As different people as different approach you can use any approach you like this is just an example.
public class ClearCookies extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
showDialog();
}
/**
* #throws NotFoundException
*/
private void showDialog() throws NotFoundException {
new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.ClearCookies))
.setMessage(
getResources().getString(R.string.ClearCookieQuestion))
.setIcon(
getResources().getDrawable(
android.R.drawable.ic_dialog_alert))
.setPositiveButton(
getResources().getString(R.string.PostiveYesButton),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
//Do Something Here
}
})
.setNegativeButton(
getResources().getString(R.string.NegativeNoButton),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
//Do Something Here
}
}).show();
}}
As told before there are number of ways doing this. this is one of the way you can do your task, please accept the answer if you feel that you have got it what you wanted.
Related
Good Day, So I have this program where the user will scan a QR code and get the value of it in the SQLite database but before I get the value the dialog box pops-up messaging me that "there is no participant found". Below is my code:
This is my onStart override.
#Override
protected void onStart()
{
super.onStart();
getparticipantid = tvParticipantID.getText().toString();
etparticipantidvalue.setText(getparticipantid);
getParticipantIbeam();
}
This is my activity where it will load the data from the database once the user scans the QR code.
private void getParticipantIbeam()
{
SQLiteFunctionUlitity.GameIBeamParticipant memberInfo = SQLiteFunctionUlitity.getparticipantIbeam(getparticipantid, mDbHelper.getSqliteObjectWithReadable());
if (memberInfo != null)
{
tvParticipantName.setText(memberInfo.getParticipantName());
tvParticipantNation.setText(memberInfo.getParticipant_nationality());
tvParticipantCategory.setText(memberInfo.getCategory());
tvWave.setText(memberInfo.getWave_number());
tvCategory.setText(memberInfo.getCategory());
}
else
{
Context context = this;
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("No Participant found in the Game.");
builder1.setCancelable(true);
builder1.setPositiveButton("Scan Again", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(GameiBeamLineTracing.this, ScanGameIbeam.class);
startActivity(intent);
finish();
}
});
builder1.setNegativeButton("Close", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
onStop();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
As you can see I call the getParticipantIbeam activity in onStart method but when I call it, it reads the else statement rather than the if statement.
I know this is a simple if else statement and lifecycle but I am desperate to know the answer.
I have used the library for scanning QR code, its very simple it may help you.
QR Code implementation library for android, Click here (blikoon)
Definitely this library will solve your all QR Code related issue and dont forget to implement run time permissions like photo , gallery etc.
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.
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.
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)
}
I am working on an android project where I am trying to show a AlertDialog in a separate normal java class and return the result that the user enters. I can display the dialog fine but the problem I am having is it always returns the value before the dialog has had one of the buttons pressed.
Below is the code that calls the function in the standard java class to show the dialog
private void showDiagreeError()
{
Common common = new Common(this);
boolean dialogResult = common.showYesNoDialog();
Toast.makeText(getApplicationContext(), "Result: " + dialogResult, Toast.LENGTH_LONG).show();
}
And below is the code that shows the actual dialogue
public boolean showYesNoDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure you do not want to agree to the terms, if you choose not to, you cannot use Boardies Password Manager")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialogResult = true;
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialogResult = false;
}
});
AlertDialog alert = builder.create();
alert.show();
return dialogResult;
}
dialogResult is a global variable visible throughout the class and being set to false. As soon as the dialog is shown the toast message is shown showing the result is false, but I was expecting the return statement to block until the user has pressed one of the buttons too set the variable to the correct value.
How can I get this to work.
After many hours hunting through the inner depths of google pages, I found this Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style).
It does exactly the job I was after and tested to make sure there are no ANR errors, which there isn't