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()
Related
Interface:-
I want to make a toast message, if user did not choose any subject, it will toast message "Please choose subject". There is no error, the issue was I dont know where to put the coding to display the toast message when needed.
Coding:-
#Override
public void onClick(View v) {
final MediaPlayer mediaPlayer = MediaPlayer.create(FilterTuitionCentreActivity.this, R.raw.soundeffect1);
if (v == filterButton) {
mediaPlayer.start();
filterBtnFlag = true;
if(spLocation.getSelectedItem() == null){
return;
}
/*if(!(spSubject.getSelectedItem().toString().equalsIgnoreCase("Subject")
|| spSubject.getSelectedItem().toString().equalsIgnoreCase("Choose Subject"))){
Toast.makeText(FilterTuitionCentreActivity.this, "Please choose subject.", Toast.LENGTH_SHORT).show();
}*/
else {
loadFilteredInstitutesList("Advertisement");
}
}
}
You need a move that validation logic up and return without go further if any validation fails.
#Override
public void onClick(View v) {
//add your spinner validity checking here
if(!(spSubject.getSelectedItem().toString().equalsIgnoreCase("Subject")
||
spSubject.getSelectedItem().toString().equalsIgnoreCase("Choose Subject"))){
Toast.makeText(FilterTuitionCentreActivity.this, "Please choose subject.", Toast.LENGTH_SHORT).show();
return;
}
final MediaPlayer mediaPlayer = MediaPlayer.create(FilterTuitionCentreActivity.
this, R.raw.soundeffect1);
if (v == filterButton) {
mediaPlayer.start();
filterBtnFlag = true;
if(spLocation.getSelectedItem() == null){
return;
}
loadFilteredInstitutesList("Advertisement");
}
}
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)
else if in my codes. Basically i have several condition to fulfill before i can start drawing circles. However upon execution of the program, the popup dialog appears several times even if the condition is met. I would only want a dialog to appear once if there is a message to display. Am i doing it the right way? PLease advice.
my codes are as follows:
if (MainActivity.isClicked() == true) {
if (condition 1) {
canvas.drawCircle(x, y, radius, redPaint);
invalidate();
} else if (condition 2) {
canvas.drawCircle(x, y, radius, bluePaint);
invalidate();
} else if (condition 3){
msg = "green not available";
} else {
msg =" please add more colors";
}
AlertDialog.Builder builder = new Builder(getContext());
builder.setTitle("Warning").setMessage(msg);
builder.setPositiveButton("Okay",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di,int i) {
}
});
builder.create().show();
}// if
Create an method for showing alert when condition meet as:
private void showAlert(String str_mesg){
AlertDialog.Builder builder = new Builder(getContext());
builder.setTitle("Warning").setMessage(str_mesg);
builder.setPositiveButton("Okay",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di,int i) {
}
});
}
Call showAlert in if-else ladder to show alert:
......
} else if (condition 3){
msg = "green not available";
showAlert(msg);
} else {
msg =" please add more colors";
showAlert(msg);
}
.....
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.
I have a activity am using a boolean condition to check some thing .if the boolean condition Satisfy i need to Go to The next Page. But When The condition Satisfy the Device get crash With NullPointerException Am giving The Code Below
The Boolean Condition
boolean check()
{
boolean matches=false;
int falseFlag=0;
if(cc.length==picarray.length)
{
for (int i=0;i<cc.length;i++)
{
if(cc[i].equals(picarray[i]))
{
//---The Database Value Stored in Array is modified---
xmin=X[i]-25;
xmax=X[i]+25;
ymin=Y[i]-25;
ymax=Y[i]+25;
//---Check Whether The Selected Password Is Inside The Array Values---
if(xmin<realx[i]&&realx[i]<xmax)
{
System.out.println("TRUE");
}
else
{
falseFlag++;
System.out.println("FALSE");
}
if(ymin<realy[i]&&realy[i]<ymax)
{
System.out.println("TRUE");
}
else
{
falseFlag++;
System.out.println("FALSE");
}
}
else
{
falseFlag++;
}
}
}
else
{
falseFlag++;
}
if(falseFlag==0)
{
matches=true;
}
System.out.println("Authentication returns "+matches);
return matches;
}
in button click
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(check())
{
Intent sa=new Intent(Test.class,Test2.class);
startActivity(sa);
System.out.println("U R AUTHENTICATED");
}
else
{
System.out.println("INVALID USER");
Toast.makeText(getApplicationContext(), "INVALID USER", Toast.LENGTH_LONG).show();
}
}
});
try this,
Intent sa=new Intent(getApplicationContext(),Test2.class);
basically intent needs context and not a class...
i doub't this (Intent sa=new Intent(Test.class,Test2.class);) will compile
The first argument is a Context so when you create the intent, it should be:
Intent sa=new Intent(Test.this,Test2.class);
instead of
Intent sa=new Intent(Test.class,Test2.class);
This should also work:
Intent sa=new Intent(v.getContext(),Test2.class);
Intent sa=new Intent(Test.class,Test2.class);
The first parameter should be Test.this(Context), is it not throwing a Compile-time error ??