How exactly to act on a confirmation dialog? - android

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.

Related

Forcing the users to update my app

how can i force user to update my app by going to Google play store? if there's a new update a dialog will show which will have 2 buttons either update app or exit app.
Wont allow app to run unless latest version.
I am using eclipse and i cant migrate to android studio because of some project issues .
please help
Use Dialogs when your main Activity starts. Just redirect the user to the URL of your app on the PlayStore if he accepts, and exit the app (here are examples on how doing it).
Took from Anrdoid documentation :
public class YourDialogFragment 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.please_update)
.setPositiveButton(R.string.Ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// launch a browser with your PlayStore APP URL
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Exit the app
android.os.Process.killProcess(android.os.Process.myPid());
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
Now, when you create an instance of this class and call show() on that object, the dialog appears as shown in figure 1.
Just create an instance of it and use the show() method in your onCreateDialog from your MainActivity.
Note that Dialogs uses Fragments, which requieres API level 11. (You should be able to check the API level you're building to in your build.gradle file)
Use dialogs as mentioned by Noafix. Call an alert dialog when your version mismatches.
Also set dialog cancelable to false so that user cant remove dialog by pressing back!
private void showDialog()
{
final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Update");
alertDialogBuilder.setMessage("Please update to continue?");
alertDialogBuilder.setIcon(R.drawable.warning);
alertDialogBuilder.setCancelable(false)
alertDialogBuilder.setPositiveButton("Confirm",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
});
// Add a negative button and it's action. In our case, just hide the dialog box
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
});
// Now, create the Dialog and show it.
final android.app.AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
You could get your version name as:
versionName = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0).versionName;
Now get your current version from your server using any rest client http calls and check with your version:
if(!versionName.equals(version)){showDialog();}
Note: For this you should implement a version file in server in which you must add new version in that file so that using http calls your app can get the new version name and check with app version!
Implement a way for the app to check if it is the latest version or not.
You can do this by hosting an update file that contains information on what the latest version is. This file is commonly in json format but can also be in any format you prefer. The app would have to query this update file and if the current version of the app is less than the version indicated in the update file, then it would show the update prompt.
If the app determines that an update is needed, open a dialog prompt then open the app's play store page
To launch a dialog prompt refer to the official Dialogs guide. Given that the question is not "how to launch a dialog" I will focus on discussing how to update the app.
To open google play store to a particular app page you must launch an intent with the View action and Market scheme uri like so
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
Be wary that if the device does not have google play store installed, then this will throw an exception. It is also possible for other apps to receive this type of intent and in the case where multiple apps can receive the intent, an app picker dialog will appear.
Challenges:
If the app must check for updates and can only run if it is the latest version, then the app cannot run if the device is not connected to the internet.
The app will have a hard dependency on google play store and cannot run if an update is needed and there is no play store on the device
If the update file is unavailable for any reason then the app will not run as well
You absolutely need the users to update to continue using the app, you could provide a simple versioning API. The API would look like this:
versionCheck API:
->Request parameters:
int appVersion
-> Response
boolean forceUpgrade
boolean recommendUpgrade
When your app starts, you could call this API that pass in the current app version, and check the response of the versioning API call.
If forceUpgrade is true, show a popup dialog with options to either let user quit the app, or go to Google Play Store to upgrade the app.
Else if recommendUpgrade is true, show the pop-up dialog with options to update or to continue using the app.
Even with this forced upgrade ability in place, you should continue to support older versions, unless absolutely needed.
try this: First you need to make a request call to the playstore link, fetch current version from there and then compare it with your current version.
String currentVersion, latestVersion;
Dialog dialog;
private void getCurrentVersion(){
PackageManager pm = this.getPackageManager();
PackageInfo pInfo = null;
try {
pInfo = pm.getPackageInfo(this.getPackageName(),0);
} catch (PackageManager.NameNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
currentVersion = pInfo.versionName;
new GetLatestVersion().execute();
}
private class GetLatestVersion extends AsyncTask
{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... params) {
try {
Document doc = Jsoup.connect(urlOfAppFromPlayStore).get();
latestVersion = doc.getElementsByAttributeValue
("itemprop","softwareVersion").first().text();
}catch (Exception e){
e.printStackTrace();
}
return new JSONObject();
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
if(latestVersion!=null) {
if (!currentVersion.equalsIgnoreCase(latestVersion)){
if(!isFinishing()){
showUpdateDialog();
}
}
}
else
background.start();
super.onPostExecute(jsonObject);
}
}
private void showUpdateDialog(){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("A New Update is Available");
builder.setPositiveButton("Update", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse
("market://details?id=yourAppPackageName")));
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
background.start();
}
});
builder.setCancelable(false);
dialog = builder.show();
}

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

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.

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

One-time AlertDialog showing on every run

I am trying to have a disclaimer pop up when the app is first run, and after each update. I did a bunch of googling and reviewed some questions here as well, and this is what my code looks like:
SharedPreferences pref = getSharedPreferences("Preferences", MODE_PRIVATE);
SharedPreferences.Editor edit = pref.edit();
String lver = pref.getString("Version", "");
String ver = this.getString(R.string.version);
if(ver != lver)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Disclaimer")
.setMessage(this.getString(R.string.disclaimer))
.setCancelable(false)
.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
accepted = true;
dialog.cancel();
}
})
.setNegativeButton("Decline", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainMenu.this.finish();
}
});
AlertDialog disc = builder.create();
disc.show();
if(accepted == true)
{
edit.putString("Version", this.getString(R.string.version));
edit.commit();
}
}
This code actually worked at first, but when I changed my apps starting activity, and moved this code from the original starting activity to the new one, it no longer works. The disclaimer appears on every run.
I want the popup only to show on first run and after updates. What do I need to do to achieve this? I am very frustrated and confused by the fact that it was working, then wasnt.
Comparing Strings with .equals() is the correct way (see: How do I compare strings in Java? for a good explanation) , although because I'm not sure how the android internals work and you said it worked before, that isn't your problem. Your problem is that your check
if (accepted == true) {/** code */}
isn't run on the on click listener. Because it isn't, that thread (I'm assuming it spawns a new thread to show the dialog) keeps running.
I'm also assuming before you moved this code, you had declared a
boolean accepted = true; //or initialized it to true somewhere
But when you moved it you didn't reinitialize it. Now, because the default value of a primitive is false, in your new code it gets to the check before you press a dialog button, and never commit the new version.
My advice would be put what's in the
accepted == true
block simply into your listener for the positive button click.

How to implement a confirmation (yes/no) DialogPreference?

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.

Categories

Resources