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();
Related
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();
}
}
Here let me explain my issue need to add volley inside alertdialog which i have done successfully its like pinging the entered Url its working fine but what I need to do is in onErrorResponse method alert dialog gets hide suppose when user enter wrong url it will go to onErrorResponse method in this my alertdialog gets hide need to stay awake the dialog even when error gets occurred so far what I have tried is:
This is my code:
final AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Add Self Hosted URL "); //Set Alert dialog title here
alert.setMessage("Enter The Url Here"); //Message here
final EditText input = new EditText(context);
alert.setView(input);
ConnectivityManager cn = (ConnectivityManager) PingingActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf != null && nf.isConnected()) {
final ProgressDialog progressDialog=new ProgressDialog(this);
progressDialog.hide();
Toast.makeText(getApplicationContext(), "Network Available", Toast.LENGTH_LONG).show();
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
progressDialog.show();
progressDialog.setMessage("Pinging Please Wait");
final String srt = input.getEditableText().toString();
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, srt,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("resp", response);
SharedPreferences settings = getSharedPreferences(PingingActivity.id, 0); // 0 - for private mode
SharedPreferences.Editor editor = settings.edit();
editor.putString("Url", srt);
editor.putBoolean("URLflag", true);
editor.apply();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// alert.show();
// input.setText(srt);
//final String srt = input.getEditableText().toString();
String str = error.toString();
if (str != null) {
Toast.makeText(getApplicationContext(), "Please Check the Entered URL", Toast.LENGTH_SHORT).show();
// progressDialog.cancel();
}
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Toast.makeText(context, srt, Toast.LENGTH_LONG).show();
}
});
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
dialog.cancel();
}
}).setIcon(R.drawable.ic_info_black_24dp).show(); //End of alert.setNegativeButton
/* Alert Dialog Code End*/
}
else {
showAlertDialog("No Network", "Please Check Your Network Connectivity", true);
}
even in onerrorresponse need to display my alertdialog how can i achieve this. It may be a dumb question but as a beginner am struggling with this can anyone help me
Create a bool method returning the status , call it
alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
return true from response and false from onError()
if the response return success start your desired Activity , otherwise let the alert dialog show.
Why am i getting this white background under my alert dialogbox. I been trying to figure out the problem for an hour and had no luck. Can someone please help me?
Also, why is that the left and right sides of the title has a little dark shade.
protected void onPostExecute(String result) {
//progressDialog.dismiss();
try {
JSONObject json = new JSONObject(result);
String status = json.getString("status");
String message = json.getString("message");
if(status.equals("true")) {
Intent intent = new Intent(context, HomeActivity.class);
intent.putExtra(LoginActivity.EXTRA_MESSAGE, status);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(message)
.setTitle("Error")
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).create().show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Import
android.support.v7.app.AlertDialog instead of android.app.AlertDialog
Change your code as -
Dialog alertDialog = new Dialog(this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.tabs);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
alertDialog.show();
Or you can add theme to your existing code.
AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
When initializing dialog builder, pass second parameter as the theme.
So Change
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
to
AlertDialog.Builder builder = new AlertDialog.Builder(activity, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
It is old answer, now
Import android.support.v7.app.AlertDialog instead of android.app.AlertDialog
as given in accepted answer.
if you can access Dialog class, try this:
alertDialog.getWindow().getDecorView().setBackgroundColor(Color.TRANSPARENT);
before:
after:
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 new in Android and I am attempting to Send an SMS through an Android application. I need it such that if the Message Contains the Word "MYSELF" Prompt the user whether they want to go ahead to send the SMS My Method is :
public void sendSmsByManager() {
try {
// Get the default instance of the SmsManager
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber.getText().toString(),
null,
smsBody.getText().toString(),
null,
null);
//If the SMS Contains the WORD MYSELF Prompt the User If they Want to send the SMS
Toast.makeText(getApplicationContext(),
"Your sms has successfully sent!",
Toast.LENGTH_LONG).show();
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
How can I achieve this?
Create an Alert Confirmation style dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Some Message");
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//send text
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//discard text
}
});
AlertDialog dialog = builder.create();
dialog.show();
This will work for you :
public void sendSmsByManager() {
try {
//If the SMS Contains the WORD MYSELF Prompt the User If they Want to send the SMS
if (smsBody.getText().toString().contains("MYSELF")){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("SMS CONTAINS MYSELF! Do you really Want to send this SMS"); // It will set the message you want to display
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Get the default instance of the SmsManager
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber.getText().toString(),
null,
smsBody.getText().toString(),
null,
null);
Toast.makeText(getApplicationContext(),
"Your sms has successfully sent!",
Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}