My dialog gets open and ask for code but when user switches to message box of mobile phone to see the code by minimizing the app.Then after resumes the app the dialog box disappears.
My app is unable to restore last UI State.
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Enter Your Registeration Code");
alert.setMessage("Registeration code has been delivered on your registered number via sms");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setCancelable(false);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString().trim();
String regsCode2 = etFake.getText().toString().trim();
if (value.compareToIgnoreCase(regsCode2) == 0) {
validCodeMatch = objCommonServices.sendEvalidCode(String.valueOf(mobileNo), password, "OK", regsCode2);
if (validCodeMatch.contains("Code Match")) {
showDialog(2);
}
} else {
try {
removeDialog(3);
showDialog(3);
} catch (Exception e) {
}
}
}
});
Related
I created this method to handle 2 different way of creating alert dialog, depending on internet status. Do you know a better way to get the same result? Using .equals() on strings in if-else block do not seem a best-practices way... Am i right?
public void noInternetAlertDialog(String errorMsg) {
String title = null;
String msg = null;
if (errorMsg.equals("none")) {
title = "Connection failded";
msg = "Please check internet connection";
} else if (errorMsg.equals("slow")) {
title = "Connection timeout";
msg = "Connection is slow";
}
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(Main.this);
builder.setCancelable(false);
builder.setTitle(title);
builder.setMessage(msg);
builder.setPositiveButton("Retry", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
downloadDialog();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
Use strings.xml for your strings to allow localization (Retry, Cancel, "Connection failded", "Please check internet connection", "Connection timeout", "Connection is slow")
If your values represent something create a data type for them. I mean: if your string will report if internet is available or slow, why keep it as String? A String can be everything and convert to something which says directly what values it can assume will improve your code a lot.
public enum InternetStatus {
Offline,
Slow
}
And a == will be faster than a equals call.
If you don't want to use the enum, consider using "none".equals(errorMessage)
String title = "Connection failded";
String msg = "Please check internet connection";
if ("slow".equals(errorMsg)) {
title = "Connection timeout";
msg = "Connection is slow";
}
You can chain calls to the builder and remove the variable dialog because you can call show() directly (If you still need the reference to the AlertDialog, show() still returns it).
You can go with your fantasy and do something like this
.setTitle(errorMsg == InternetStatus.Slow ? "Connection timeout" : "Please check internet connection")
.setMessage(errorMsg == InternetStatus.Slow ? "Connection failded" : "Connection is slow")
but it will make your code a mess if you want to add more InternetStatus.
You could create a method inside InternetStatus which returns the message (if it will be needed in other places too). But it highly depends on the project you are working with. You could an "extension" method which does it for you just where you need it without put it in the enum code (enums can have methods). You should consider every opportunity.
Maybe?
public enum InternetStatus {
Offline,
Slow
}
public void noInternetAlertDialog(InternetStatus errorMsg) {
String title = getString(R.string.internetfailed);
String msg = getString(R.string.checkyourinternet);
if (errorMsg == InternetStatus.Slow) {
title = getString(R.string.connectiontimeout);
msg = getString(R.string.slowinternet);
}
new AlertDialog.Builder(Main.this)
.setCancelable(false)
.setTitle(title)
.setMessage(msg)
.setPositiveButton(R.string.retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
downloadDialog();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
})
.show();
}
It really is not a good idea to identify a state/result with a string! you should use an enum instead.
enum NoInternetResult {
slow, none
}
and then:
public void noInternetAlertDialog(NoInternetResult result) {
String title = "Connection failded";
String msg = "Please check internet connection";
if (result==NoInternetResult.slow) {
title = "Connection timeout";
msg = "Connection is slow";
}
btw. use strings.xml for you strings like "retry" and "Cancel" (http://developer.android.com/guide/topics/resources/string-resource.html)
public void sendTextMessage1(
final String destinationAddress, final String scAddress, final String text,
final PendingIntent sentIntent, final PendingIntent deliveryIntent){
if (TextUtils.isEmpty(destinationAddress)) {
throw new IllegalArgumentException("Invalid destinationAddress");
}
if (TextUtils.isEmpty(text)) {
throw new IllegalArgumentException("Invalid message body");
}
try {
final ISms iccISms = ISms.Stub.asInterface(ServiceManager.getService("isms"));
if (iccISms != null)
{
if( destinationAddress.length()<10 )
{
new AlertDialog.Builder(null, 0).setTitle("SEND MESSAGE")
.setMessage("Are you sure you want to send this msg to no ? "+ destinationAddress)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with sending
try
{
iccISms.sendText(destinationAddress, scAddress, text, sentIntent, deliveryIntent);
}
catch (RemoteException ex) {
// ignore it
}
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
else
{
try
{
iccISms.sendText(destinationAddress, scAddress, text, sentIntent, deliveryIntent);
}
catch (RemoteException ex) {
// ignore it
}
}
I am following code the Dialog box , but it is not working ,can anyone suggest how to display this
you were passing context reference as null for building alertDialog,pass the context reference otherwise you will experience NPE
change new AlertDialog.Builder(null, 0) to
new AlertDialog.Builder(getApplicationContext(), 0)
This code will works for alert dialog box
public class AlertDialogManager {
/**
* Function to display simple Alert Dialog
* #param context - application context
* #param title - alert dialog title
* #param message - alert message
* #param status - success/failure (used to set icon)
* - pass null if you don't want icon
* */
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
}
Also u can add this in where u want to set the alert
alert.showAlertDialog(RegisterActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
This if-else statement I am using it onClick method of Android code.
if (input == null){
dispError();
}else{
startAct();
}
when value is true or false startAct() gets implemented;
if (input != null){
dispError();
}else{
startAct();
}
when value is true or false dispError() gets implemented;
input is a string.
actual code of my program:
#Override
public void onClick(View view) {
// Launching Display Meaning Activity
meaning = (EditText) findViewById(R.id.editText1);
input = meaning.getText().toString();
if (input == null){
dispError();
}else{
startAct();
}
}
public void startAct(){
Intent intent =new Intent("com.dictionary.khasi_english.DisplayMeaningActivity");
intent.setClass(MainActivity.this, DisplayMeaningActivity.class);
intent.putExtra(MEANING_INPUT, input);
startActivity(intent);
}
public void dispError(){
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("ERROR");
builder.setMessage("Please enter a Word.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
});
}
}
meaning.getText().toString() will never return null. However, it can return "", an empty string. Use the following code to check against that:
if(input.isEmpty()) {
dispError();
else {
startAct();
}
It is because input, as you said, could be 'true' or 'false'. In both cases input is not null. If you want your if-statement works, you should try:
if(input.equals("true")) {
startAct();
else {
dispError();
}
Assuming you are trying to check whether the user put in any text, you should use TextUtils.isEmpty, which checks against both null and empty strings:
if(TextUtils.isEmpty(input)) {
dispError();
} else {
startAct();
}
if input is a string
try to use input.length to check if it is empty
if(input.length==0)
displayerror();
because if input=""then it is not null.
you can use TextUtils.isEmpty()
I want to implement a sign up activity where user insert his/her information then click a button to send this information to web service which stored this information in a database.
I put the code for connecting to web service in a separated Thread (Not in UI Thread), and I want to display a progressdialog until the connection to web service finish, then I want to display an AlertDialog to display different messages like(this email is used try different one , or Sign up successes!)
here is the which excuse when user click sign up button :
public void SignupNewUser (View V)
{
Working = ProgressDialog.show(this, "Working..", "Connecting To Server");
Runnable work = new Runnable() {
#Override
public void run() {
Edit_Text_FName = (EditText) findViewById(R.id.Edit_Text_Fname_Signup);
Edit_Text_LName = (EditText) findViewById(R.id.Edit_Text_Lname_Signup);
Edit_Text_Password = (EditText) findViewById(R.id.Edit_Text_Password_Signup);
Edit_Text_Email = (EditText) findViewById(R.id.Edit_Text_Email_Signup);
S1 = (Spinner) findViewById(R.id.Spinner_Signup);
SignupPerson SUPerson = new SignupPerson();
SUPerson.F_Name = Edit_Text_FName.getText().toString().trim();
SUPerson.L_Name = Edit_Text_LName.getText().toString().trim();
SUPerson.E_Mail = Edit_Text_Email.getText().toString().trim();
SUPerson.PassW = Edit_Text_Password.getText().toString().trim();
SUPerson.Gen = Choosen_Gender;
SUPerson.Cou_Id = S1.getSelectedItemPosition();
METHOD = "signup";
SoapObject Request = new SoapObject(NAMESPACE, METHOD);
PropertyInfo P = new PropertyInfo();
P.setName("SUPerson");
P.setValue(SUPerson);
P.setType(SUPerson.getClass());
Request.addProperty(P);
SoapSerializationEnvelope envolope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
envolope.dotNet = true;
envolope.setOutputSoapObject(Request);
envolope.addMapping(NAMESPACE, "SignupPerson", new SignupPerson().getClass());
HttpTransportSE ahttp = new HttpTransportSE(URL);
SoapPrimitive Res = null;
try
{
ahttp.call(NAMESPACE+METHOD, envolope);
Res = (SoapPrimitive) envolope.getResponse();
}
catch (Exception ex)
{
//ex.printStackTrace();
result = -1;
}
if (result != -1)
{
result = Integer.parseInt(Res.toString());
}
Working.dismiss();
}
};
Thread SS = new Thread(work);
SS.start();
switch (result)
{
case -1:
showDialog(-1);
break;
case 0:
showDialog(0);
break;
case 1:
showDialog(1);
break;
case 2:
showDialog(2);
break;
default:break;
}
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case -1:
return new AlertDialog.Builder(this)
.setTitle("error!")
.setMessage("error connecting to the server. please try again")
.setIcon(R.drawable.ic_error)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
})
.create();
case 0:
return new AlertDialog.Builder(this)
.setTitle("error!")
.setMessage("You have entered an Exists Email, Please try another one")
.setIcon(R.drawable.ic_error)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}).create();
case 1:
return new AlertDialog.Builder(this)
.setTitle("error!")
.setMessage("Server Error, Please Try Again Later")
.setIcon(R.drawable.ic_error)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
})
.create();
case 2:
return new AlertDialog.Builder(this)
.setTitle("Registration successfully!")
.setMessage("Click OK to Sign in and Start Usign Hello!!")
.setIcon(R.drawable.ic_success)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
Intent i = new Intent(SignupActivity.this ,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
})
.create();
}
return null;
}
here , SUPerson is an object which hold user information, and result is an integer which indicate which AlertDialog will display after connection to web service end.
my question is that when I run the above code ,, No Alert Dialog message appear !
why ?
If you use an AsyncTask you will have a much easier time doing this. I think you might not be getting your dialog because you're trying to show it immediately after starting the thread.
With the AsyncTask, you can have your server connection running in doInBackground() on a separate thread and then you can have your dialog called in onPostExecute().
Let me know if that makes sense! The link is pretty clear on how to use it. :)
Edit: I also wanted to mention, if you use the AsyncTask, it allows you to easily set up a ProgressDialog in the onProgressUpdate() method.
I have an alert dialog box in my application for login authentication. While sending the request i want to show a progress bar and want to dismiss if the response is success.please help me if anyone knows.Iam using the below code:
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
LinearLayout login = new LinearLayout(this);
TextView tvUserName = new TextView(this);
TextView tvPassword = new TextView(this);
TextView tvURL = new TextView(this);
final EditText etUserName = new EditText(this);
final EditText etPassword = new EditText(this);
final EditText etURL = new EditText(this);
login.setOrientation(1); // 1 is for vertical orientation
tvUserName.setText(getResources().getString(R.string.username));
tvPassword.setText(getResources().getString(R.string.password));
tvURL.setText("SiteURL");
login.addView(tvURL);
login.addView(etURL);
login.addView(tvUserName);
login.addView(etUserName);
login.addView(tvPassword);
etPassword.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
login.addView(etPassword);
alert.setView(login);
alert.setTitle(getResources().getString(R.string.login));
alert.setCancelable(true);
alert.setPositiveButton(getResources().getString(R.string.login),
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
int whichButton) {
strhwdXml = etURL.getText().toString();
strUserName = etUserName.getText().toString();
XmlUtil.username = strUserName;
strPassword = etPassword.getText().toString();
if ((strUserName.length() == 0)
&& (strPassword.length() == 0)
&& (strhwdXml.length() == 0)) {
Toast.makeText(
getBaseContext(),
getResources().getString(
R.string.userPassword),
Toast.LENGTH_SHORT).show();
onStart();
} else {
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor prefsEditor = prefs
.edit();
try {
StringBuffer inStreamBuf = new StringBuffer();
inStreamBuf = XmlUtil
.getLoginAuthResponse(strUserName,
strPassword, strhwdXml);
strXmlResponse = inStreamBuf.toString();
Log.e("Response:", strXmlResponse);
String parsedXML = ParseResponse(strXmlResponse);
if (parsedXML
.equalsIgnoreCase(getResources()
.getString(R.string.success))) {
}
It might be easier to use this
ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",
"Loading. Please wait...", true);
You can read more about progress dialogs here
To cancel would be
dialog.dismiss();
This class was deprecated in API level 26. ProgressDialog is a modal
dialog, which prevents the user from interacting with the app. Instead
of using this class, you should use a progress indicator like
ProgressBar, which can be embedded in your app's UI. Alternatively,
you can use a notification to inform the user of the task's progress.For more details Click Here
Since the ProgressDialog class is deprecated, here is a simple way to display ProgressBar in AlertDialog:
Add fields in your Activity:
AlertDialog.Builder builder;
AlertDialog progressDialog;
Add getDialogProgressBar() method in your Activity:
public AlertDialog.Builder getDialogProgressBar() {
if (builder == null) {
builder = new AlertDialog.Builder(this);
builder.setTitle("Loading...");
final ProgressBar progressBar = new ProgressBar(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
progressBar.setLayoutParams(lp);
builder.setView(progressBar);
}
return builder;
}
Initialize progressDialog:
progressDialog = getDialogProgressBar().create();
Show/Hide AlertDialog whenever u want using utility methods:
progressDialog.show() and progressDialog.dismiss()
If you want the progress bar to show, try the following steps and also you can copy and paste the entire code the relevant portion of your code and it should work.
//the first thing you need to to is to initialize the progressDialog Class like this
final ProgressDialog progressBarDialog= new ProgressDialog(this);
//set the icon, title and progress style..
progressBarDialog.setIcon(R.drawable.ic_launcher);
progressBarDialog.setTitle("Showing progress...");
progressBarDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//setting the OK Button
progressBarDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,
int whichButton){
Toast.makeText(getBaseContext(),
"OK clicked!", Toast.LENGTH_SHORT).show();
}
});
//set the Cancel button
progressBarDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton){
Toast.makeText(getApplicationContext(), "Cancel clicked", Toast.LENGTH_SHORT).show();
}
});
//initialize the dialog..
progressBarDialog.setProgress(0);
//setup a thread for long running processes
new Thread(new Runnable(){
public void run(){
for (int i=0; i<=15; i++){
try{
Thread.sleep(1000);
progressBarDialog.incrementProgressBy((int)(5));
}
catch(InterruptedException e){
e.printStackTrace();
}
}
//dismiss the dialog
progressBarDialog.dismiss();
}
});
//show the dialog
progressBarDialog.show();
The cancel button should dismiss the dialog.
Try below code
private class DownloadingProgressTask extends
AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(ShowDescription.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
// write your request code here
**StringBuffer inStreamBuf = new StringBuffer();
inStreamBuf = XmlUtil
.getLoginAuthResponse(strUserName,
strPassword, strhwdXml);
strXmlResponse = inStreamBuf.toString();
Log.e("Response:", strXmlResponse);
String parsedXML = ParseResponse(strXmlResponse);
if (parsedXML
.equalsIgnoreCase(getResources()
.getString(R.string.success))) {**
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (success) {
Toast.makeText(ShowDescription.this,
"File successfully downloaded", Toast.LENGTH_LONG)
.show();
imgDownload.setVisibility(8);
} else {
Toast.makeText(ShowDescription.this, "Error", Toast.LENGTH_LONG)
.show();
}
}
}
and call this in onclick event
new DownloadingProgressTask().execute();