If the location is disabled I want to show box and stop the execution process until I turn ON the location and come back to my app. Please Help with necessary suggestions.
function,
alertDialog.setTitle("GPS Setting");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("OK ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(mContext, "Sorry we cannot proceed", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();// Showing Alert Message
You should use ProgressDialog at https://developer.android.com/reference/android/app/ProgressDialog.html
see this example:
private ProgressDialog progressDialog;
public void cerrarSession() {
try {
showDialog();
// do something
} catch (InternetException e) {
// some exception
e.printStackTrace();
}
}
private void showDialog() {
progressDialog = new ProgressDialog(SavingsRequestsManager.getActivity());
progressDialog.setCancelable(false);
closeDialog();
progressDialog.setMessage(SavingsRequestsManager.getActivity().getString(R.string.progress));
progressDialog.show();
}
public void closeDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
Related
I am having a dialog which must execute some code on canceled. I set a negative button but its not executing when dialog is canceled from back button.
here is my code.
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Licence expired");
builder.setCancelable(false);
builder.setMessage("Your licence for " + url
+ " has been expired, Please renew it or select another server");
builder.setPositiveButton("Renew now",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Open url in webview
Intent intent = new Intent(MainActivity.this,
WebActivity.class);
intent.putExtra("ServerDomain", url);
startActivity(intent);
/*
* URL domain; try { domain = new URL(url);
* intent.putExtra("ServerDomain", domain.getHost());
* startActivity(intent); } catch (MalformedURLException
* e) { e.printStackTrace(); }
*/
/*
* String url = "http://www.google.com"; Intent i = new
* Intent(Intent.ACTION_VIEW);
* i.setData(Uri.parse(url)); startActivity(i);
*/
}
});
builder.setNegativeButton("Switch Server",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showServerList();
}
});
builder.create().show();
Create a cancel listner for dialog.
builder.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
showServerList();
}
});
I made an abstract fragment that other fragments extend with the following:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Thread.UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
paramThrowable.printStackTrace(printWriter);
String s = writer.toString();
Utils.logToFile(s);
emailReport(s); ///<<<<<
if (oldHandler != null) oldHandler.uncaughtException(paramThread, paramThrowable); //Delegates to Android's error handling
else System.exit(2); //Prevents the service/app from freezing
}
});
}
Just before handing the process back to the OS (after storing the exception in a file) I call emailReport(s);
private void emailReport(final String report) {
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.crash_report))
.setMessage(getString(R.string.send_crash_report))
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_SUBJECT, "Crash Report");
intent.putExtra(Intent.EXTRA_TEXT, report);
Intent mailer = Intent.createChooser(intent, null);
startActivity(mailer);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
I want the alert dialog to show before the OS takes control so the user can either open his email client to send me the crash or cancel and close the app. The debug stops on the line that creates the alert dialog but after that, it jumps to the end of this method and from there, back to the old handler.
It could be another exception but I don't know that for sure and I can't catch it because I'm already in the middle of processing the current exception. Is there something wrong in the code? if not, how can I see what happens when trying to create the alert dialog?
UPDATE: I put the handling lines inside the setNegativeButton of the dialog, thinking it was shown but immediately closed but it didn't help:
if (oldHandler != null) oldHandler.uncaughtException(paramThread, paramThrowable); //Delegates to Android's error handling
else System.exit(2); //Prevents the service/app from freezing
}
I guess the problem is that you call imediatly the default handler which internally calls exit so your dialog is never been shown. So you method should look like this:
private void emailReport(final String report,
final Thread.UncaughtExceptionHandler oldHandler) {
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.crash_report))
.setMessage(getString(R.string.send_crash_report))
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:support#example.com"));
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_SUBJECT, "Crash Report");
intent.putExtra(Intent.EXTRA_TEXT, report);
Intent mailer = Intent.createChooser(intent, null);
startActivity(mailer);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if(oldHandler != null) {
//Delegates to Android's error handling
oldHandler.uncaughtException(paramThread, paramThrowable);
} else {
// Force to close the app now after handling the crash bug
System.exit(2);
}
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
And don't miss to remove the last two lines:
if (oldHandler != null) oldHandler.uncaughtException(paramThread, paramThrowable); //Delegates to Android's error handling
else System.exit(2); //Prevents the service/app from freezing
I am trying to use parse.com in an android application of mine, how to get the context at the place of *** in the code AlertDialog.Builder(*******)? I tried using getApplicationcontext which doesn't work.Can anyone with experience in the android help me with respect to this?
mSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mVibrator.vibrate(100);
//Checking for internet connection...
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//internet connection inactive... show alert...
if (!(netInfo != null && netInfo.isConnectedOrConnecting())) {
AlertDialog.Builder adb = new AlertDialog.Builder(arg0.getContext());
adb.setTitle("ALERT");
adb.setMessage("Please turn on Internet.");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Ok' Button
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Cancel' Button
dialog.cancel();
}
});
adb.setIcon(R.drawable.ic_launcher);
adb.show();
}else{
ParseQuery<ParseObject> query = ParseQuery.getQuery("Admin");
query.whereEqualTo("password", mUserNameEditText.getText().toString());
query.whereEqualTo("userName", mPasswordEditText.getText().toString());
query.countInBackground(new CountCallback() {
public void done(int count, ParseException e) {
if (e == null) {
// The count request succeeded. Log the count
Log.d("test", "Sean has played " + count + " games");
if(count>0){
// save the login status... loggedIn/notloggedIn...
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginScreenActivity.this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isLoggedIn", true);
editor.commit();
// if user name password is correct, navigate to next activity...
Intent intent = new Intent(LoginScreenActivity.this,OptionScreenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, 0);
overridePendingTransition(R.layout.fade_in, R.layout.fade_out);
}else{
AlertDialog.Builder adb = new AlertDialog.Builder(*********************);
adb.setTitle("ALERT");
adb.setMessage("Wrong username or password.");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Ok' Button
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Cancel' Button
dialog.cancel();
}
});
adb.setIcon(R.drawable.ic_launcher);
adb.show();
}
} else {
// The request failed
}
}
});
Try out as below:
AlertDialog.Builder adb = new AlertDialog.Builder(getApplicationContext());
OR
AlertDialog.Builder adb = new AlertDialog.Builder(<YourActivity>.this);
I'm trying to show an alert dialog when a user fails to enter valid email and password to log in. Since the login process has to deal with HTTP request and JSON, I put it all in an AsyncTask and I'm not sure if that's the problem why my alert dialog can't show (I hope not). So this is method checkUser, which is called within onPostExecute of the AsyncTask class:
public void checkUser(JSONObject json){
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
if (tag == login_tag){
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
// code omitted
} else{
// Error in login
mProgressDialog.dismiss();
builder.setMessage("Incorrect username/password")
.setTitle("Error")
.setNeutralButton("OK", new OnClickListener() {
public void onClick(final DialogInterface dialog,final int which) {
dialog.cancel();
}
}).create().show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Somehow my alert dialog can never show and I don't know why. If you have any idea what the reason of this problem is, please help me out. Thanks a lot!
EDIT: Turns out I only close my Progress Dialog after executing this method, so I decided to dismiss it before showing the alert dialog. But it still hasn't solved the problem.
So I solved this myself this way: somehow the Alert dialog only works outside the method checkUser. So I move the bits within the error if clause outside, below the dismiss() of Progress dialog in onPostExecute():
protected void onPostExecute(JSONObject json) {
checkUser(json);
mProgressDialog.dismiss();
try {
if (json.get(ERROR_MSG) != null){
String errorMsg = json.getString(ERROR_MSG);
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage(errorMsg)
.setTitle("Error")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create().show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And voila, it works!
P.s: I still don't know why the dialog can't show when put within checkUser though.
missing builder.create()
// Error in login
builder.setMessage("Incorrect username/password")
.setTitle("Error")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
dialog.cancel();
}
}).create().show();
i'm working on gpsprovider,If user click on a gps based applications for suppose map application it has check whether the gps provider enabled or not if not alert the user enable the gpsprovider .
There will be a Broadcast Receivier.
Will define a message for requesting the service from any application. Will start service if not started.
Will define a message for stating that the application no longer needs it. Will stop service if no app needs it anymore
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider != null ){
if(! provider.contains("gps")){
// Notify users and show settings if they want to enable GPS
new AlertDialog.Builder(MessagePage.this)
.setMessage("GPS is switched off. enable?")
.setPositiveButton("Enable GPS", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, 5);
}
})
.setNegativeButton("Don't do it", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 5 && resultCode == 0){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider != null){
switch(provider.length()){
case 0:
//GPS still not enabled..
break;
default:
Toast.makeText(this, "GPS is now enabled.", Toast.LENGTH_LONG).show();
break;
}
}
}
else{
//the user did not enable his GPS
}
}
AFAIK it is still not possible to start the GPS service programatically. The only thing you can do is open the settings page for the user to change the setting them selves:
if(!LocationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER ))
{
Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS ); startActivity(myIntent);
}
In your CommonUtils.java
public class CommonUtils {
public static void displayPromptForEnablingGPS(
final Activity activity)
{
final AlertDialog.Builder builder =
new AlertDialog.Builder(activity);
final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
final String message = "Enable either GPS or any other location"
+ " service to find current location. Click OK to go to"
+ " location services settings to let you do so.";
builder.setMessage(message)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
activity.startActivity(new Intent(action));
d.dismiss();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
d.cancel();
}
});
builder.create().show();
}
}
In your activity
private void getGPSInfo() {
LocationManager locationmanager = (LocationManager) getActivity()
.getSystemService(Context.LOCATION_SERVICE);
if (locationmanager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// YOUR MAPS ACTIVITY CALLING or WHAT YOU NEED
} else {
CommonUtils.displayPromptForEnablingGPS(getActivity());
}
}