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)
Related
This question already has answers here:
Android check internet connection [duplicate]
(20 answers)
Closed 7 years ago.
This is not a duplicated question, I now how to check if there is internet connection, what I don't know is how to pop dialog in while loop and try again until internet connection is back
I am trying to pop Alert dialog if there is no internet connection,
and then wait for the user to hit "Try Again"
when he hit the button, check the internet connection and pop again this Alert Dialog if there is no internet connection.
When I am doing this with if statement it works good - pop the dialog when there is no internet and check for connection when hit "Try Again"
But, when I try to put this in a while loop the loop doesn't wait/show the dialog to the user.
What is the right way to do this? and why it is not working now?
while (netInfo == null || !netInfo.isConnected()) {
new AlertDialog.Builder(this)
.setTitle("title")
.setMessage("message")
.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
netInfo = cm.getActiveNetworkInfo();
System.out.println("cm: "+cm+ " netinfo: "+ netInfo);
}
})
.show();
}
try this code call getDATA() method while onCreate() in actvity , it may help
private void getDATA() {
boolean isProcess;
try {
isProcess = Utils.isNetworkConnected(class.this) || Utils.hasActiveInternetConnection(); //method to check internet connection
} catch (Exception e) {
isProcess = false;
e.printStackTrace();
}
if (isProcess) {
try {
AlertDialog.Builder builder =
new AlertDialog.Builder(class.this, R.style.AppCompatAlertDialogStyle);
builder.setTitle(getResources().getString(R.string.app_name));
builder.setMessage("Internet not available?");
builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
getDATA();
}
});
builder.setCancelable(false);
builder.show();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Crouton.makeText(class.this, MessageConstant.MsgWiFi, Style.ALERT).show();
}
}
I am working on a GroupChat process. I have successfully sent the invitation and using PSI i have received this invitation. But M unable to invoke my own "MultiUserChat.addInvitationListener". I have done this many ways but in-vain. Here is one of my attempt.
ProviderManager pm = ProviderManager.getInstance();
pm.addExtensionProvider("x", "http://jabber.org/protocol/muc#user", new MUCUserProvider());
MultiUserChat.addInvitationListener(mXmppConnection, MyClass.this);
And doing "MyClass extends Activity implements InvitationListener"
#Override
public void invitationReceived(final Connection conn,final String room, final String inviter, String reason, String password, Message message) {
AlertDialog.Builder builder = new AlertDialog.Builder(MyClass.this);
builder.setTitle("Room Invitation");
builder.setMessage(inviter + " sent you an invitation to join GroupChat saying \""+reason+" \". \n Do you want to join "+inviter+"?");
builder.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
// Joining Room
#Override
public void onClick(DialogInterface dialog, int which) {
try {
MultiUserChat multiUserChat = new MultiUserChat(conn, room);
multiUserChat.join(myNickName);
if(multiUserChat.isJoined()){
dialog.cancel();
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
});
builder.setNegativeButton("Decline", new DialogInterface.OnClickListener() {
// Declining Room Invitation
#Override
public void onClick(DialogInterface dialog, int which) {
MultiUserChat.decline(conn, room, inviter, "I'm busy right now");
dialog.cancel();
}
});
builder.show();
}
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);
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 am new to android. I want to show progress dialog when user click on login button. I tried this but the dialog is not showing
btn_logIn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
getUserCredentials();
}
}); //end of anonymous class
private void showProgressDialog() {
if (dialog == null) {
dialog = new ProgressDialog(this);
}
dialog.setMessage("Please Wait. Your authentication is in progress");
dialog.setButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
dialog.dismiss();
}
}); //end of anonymous class
dialog.show();
} //end of showProgressDialog()
private void getUserCredentials() {
EditText txt_userName = (EditText) findViewById(R.id.txt_userName);
String userName = txt_userName.getText().toString();
EditText txt_password = (EditText) findViewById(R.id.txt_password);
String password = txt_password.getText().toString();
if (userName != null && !userName.trim().equals("") && password != null && !password.trim().equals("")) {
showProgressDialog();
callWebService(userName, password);
}
} //end of getUserCredentials()
private void callWebService(String userName, String password) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("userName", userName);
....
Object result = envelope.getResponse();
if (result.equals("true")) {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
} else {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
}
} catch (SocketTimeoutException e) {
dialog.dismiss();
Toast.makeText(this, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show();
} catch(Exception e) {
e.printStackTrace();
dialog.dismiss();
Toast.makeText(this, "Unable to connect, please try again later. Thank you", Toast.LENGTH_LONG).show();
}
} //end of callWebServide()
Am i doing anything wrong. When i click on login button and service is not running then it shows message that Service is not connected, Please make sure your server is running", but the dialog isn't showing...Why? My logic is when user click on login button and fields have values then start showing progress dialog and if anything happens like when result come or server is not running or if any exception happen , then i remove the dialog and show the appropriate message, but dialog isn't showing...Why? What i am doing wrong? Please help..
Thanks
Try this,
Change your getUserCredentials() like this,
private void getUserCredentials() {
EditText txt_userName = (EditText) findViewById(R.id.txt_userName);
String userName = txt_userName.getText().toString();
EditText txt_password = (EditText) findViewById(R.id.txt_password);
String password = txt_password.getText().toString();
if (userName != null && !userName.trim().equals("") && password != null && !password.trim().equals("")) {
showProgressDialog();
Thread t=new Thread(new Runnable() {
public void run() {
callWebService(userName, password);
}
}); t.start();
}
}
And your callWebService method like this,
private void callWebService(String userName, String password) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("userName", userName);
....
Object result = envelope.getResponse();
if (result.equals("true")) {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
} else {
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
}
});
}
} catch (SocketTimeoutException e) {
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
Toast.makeText(this, "Service is not connected, Please make sure your server is running", Toast.LENGTH_LONG).show();
}
});
} catch(Exception e) {
e.printStackTrace();
ActivityName.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
Toast.makeText(this, "Unable to connect, please try again later. Thank you", Toast.LENGTH_LONG).show();
}
});
}
}
Update 1
To answer your questions from your comments,
1)Yes Async Task is more efficient. It has its own methods to do the same task what I have described here.
AsyncTask has the following methods,
i)onPreExecute()-which can be used to start your Dialog
ii)doInBackground()-which acts as the background thread.
iii)onPostExecute()-which gets called at the end where you can dismiss the dialog.
The reason why I didn't mention is that, there are possibilities that you might have to change your working code's structure to adapt to Async task.
2)runonUiThread- as the name indicates, anything inside this will be considered as it is running in the main UI thread. So basically to update the screen you have to use this. There are also other methods available, like Handlers which can also do the same task.
Use AsyncTask for it when ever task started at that time initialise your widget and then call your webservice from run method and close your progress bar on stop method.