how to use Alert Box? - android

I have an application that uses data stored on the SD card, but my problem, I want to display a dialog box with error message before the application terminates. I tried to create a dialog box not in activity but in a simple class. the code that i use is unkown. for the first part and the second every thing is ok. when the SD card is installed and when i use a nexus google Tablet. I would like to have a message that their is no SDCard before that application crashed, or to start an other Activity used to tell the user that application need an Sdcard. the code that i use is given below. My application print the Log the crash when their is no SDcard.
public File getRootDirectory()
{
if (this.rootDirectory == null)
{
File sdCardRoot = MainApplication.getInstance().getSDCardRootDirectory();
if (sdCardRoot != null)
{
this.rootDirectory = sdCardRoot;
}
else if(Build.BRAND.equals("google"))
{
this.rootDirectory = Environment.getExternalStoragePublicDirectory(MainApplication.Appli_DIRECTORY);
} else {
Log.d(CLASS_TAG, " their is no carte Sd ");
/**
* I am trying to start a Fail Activity
*/
//Intent intent = new Intent(context, FailActivity.class)
//.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//context.startActivity(intent);
}
Log.i(CLASS_TAG, "Root directory set to :" + this.rootDirectory.getAbsolutePath());
}
return this.rootDirectory;
}

Try this
boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(!isSDPresent)
{
// yes SD-card is present
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Sorry,SD Card not Found")
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.setCancelable(false);
// Create the AlertDialog object and return it
builder.create();
builder.show();
}

Probably you must create the alertbox in the UI Thread.

Related

Android Acitivity Life Cycle Handling error

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.

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

Show Alert Dialog from Activity after activity returned result from a Fragment

The title might not be very clear, its kind of hard to explain in a short title. But here is the problem.
I have an activity, MainActivity which then shows an activity at start to show FragmentA. In MainActivity there is a menu that is shown which is accessible via FragmentA. From the menu in FragmentA the user clicks on Generate Password which then calls another activity called GeneratePassword called using startActivityForResult. When the user presses the submit button the user is then sent back to FragmentA and the function onActivityResult within the MainActivity. Within this function, I then make use of a common class which allows me to show an AlertDialog with Yes and No Buttons. OnActivityResult works fine if I take out the common.showYesNoDialog() if statement, but when this is being used I get an exception
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
Below is the code that starts the GeneratePassword Activity
Intent generatePasswrodIntent = new Intent(mMainActivity, GeneratePassword.class);
startActivityForResult(generatePasswrodIntent, AddNewLogin.GENERATE_PASSWORD);
return(true);
Below is the code that sets the result from the GeneratePassword activity
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("password", generatePassword.generatePassword());
intent.putExtras(bundle);
setResult(AddNewLogin.GENERATE_PASSWORD, intent);
finish();
Below is the code from the onActivityResult that shows the alert dialog
Bundle bundle = data.getExtras();
String password = bundle.getString("password");
Log.d("PASSWORD", password);
if (common.showYesNoDialog("Your Generated Password Is:\n " + password + "\nDo you want to copy this to the clipboard?", false))
{
ClipboardManager clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(password);
}
Below is the YesNoDialog function, but I know this works fine as I have used it in several places within my app without problem.
final Handler handler = new Handler()
{
#Override
public void handleMessage(Message mesg)
{
throw new RuntimeException();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(isCancelable);
builder.setMessage(message)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialogResult = true;
handler.sendMessage(handler.obtainMessage());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialogResult = false;
handler.sendMessage(handler.obtainMessage());
}
});
AlertDialog alert = builder.create();
alert.show();
try
{
Looper.loop();
}
catch (RuntimeException ex)
{
Log.d("Dialog Error", ex.toString());
}
return dialogResult;
And below is how I am initialising the common class
Common common = new Common(getApplicationContext());
Instead of getApplicationContext, I've tried using this but doesn't make any difference.
I just don't understand what is happening here.
Thanks for any help you can provide
The problem is in your showYesNoDialog(). What does the boolean parameter for your showYesNoDialog() method do?

How to show messages in alertdialog randomly

I am using AlertDialog to show any message and links, I use this code. But I want to show a different message (link) in every action randomly. Is that possible? and if it is, can you give me sample codes for this. thanks.
final AlertDialog d = new AlertDialog.Builder(this)
.setPositiveButton(android.R.string.ok, null)
.setIcon(R.drawable.icon)
.setMessage(Html.fromHtml("Check this link out"))
.create();
d.show();
// Make the textview clickable. Must be called after show()
((TextView)d.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());
what i want is: when user opens my application, my alertbox shows a link but i want to use many links and show them randomly, I will use it for like text ads. I mean when user open my app google.com will be shown and another time yahoo.com and another time a different link. Hope i am clear
You can use this:
public static void showAlertDialog(final String title, String message,
final Context context, final boolean redirectToPreviousScreen) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
alertbox.setMessage(message);
alertbox.setTitle(title);
alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
try{
alertbox.show();
}catch (Exception b) {
}
}

Android save instance state for dialog

I have the following radio button dialog which works the way i want i also have size 12 set as the default as well but what i need to now be able to do is save the instancestate that is when something else is selected i want that size to be selected when the app is opened again. Here is my code
final CharSequence[] items = {"12m", "16m", "20m"};
AlertDialog.Builder builder = new AlertDialog.Builder(Tweaks.this);
builder.setTitle("Select a size");
builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item] == "12m"){
Toast.makeText(this, "your size is 12", Toast.LENGTH_SHORT).show();
}
if(items[item] == "16m"){
Toast.makeText(this, "your size is 16", Toast.LENGTH_SHORT).show();
}
if(items[item] == "20m"){
Toast.makeText(this, "your size is 20", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
Thank you for any help
How to save the state of an Android CheckBox when the users exits the application?
However keep in mind this is a controlled save state. If your program should be killed due to lack of resources, you should save all appropriate info during onSaveInstanceState () and onRestoreInstanceState ()
Save the last selected instance state in perference file using SharedPreferences, then in your code always read the state from preference file when open the dialog, if no perference file existing, then use default.

Categories

Resources