multiple check or,and in if statement - android

hi i'm wonder why my if always Toast me : "names Successfully saved!"
i'm try every thing.
public void btnSave_Clicked(View view) {
TextView txtOname = (TextView)findViewById(R.id.txtOname);
TextView txtXname = (TextView)findViewById(R.id.txtXname);
String X = txtXname.getText().toString();
String O = txtOname.getText().toString();
if((X!="") && (O!="")){
DatabaseHelper.insertName(getBaseContext(),((TextView)findViewById(R.id.txtOname))
.getText().toString());
DatabaseHelper.insertName(getBaseContext(),((TextView)findViewById(R.id.txtXname))
.getText().toString());
Toast.makeText(this,"names Successfully saved!",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"E",Toast.LENGTH_SHORT).show();
}
}
}

Strings are reference types in Java, and thus the reference of a dynamically created empty string will be different from your variables. Another option to isEmpty is equals.
if (!x.equals("") && !o.equals(")) {
//code
}
Though I'd probably go with isEmpty

Replace your if statement with:
if (!x.isEmpty() && !o.isEmpty()) {
//code
}
operator == compares Object reference.
.equals() compares String value.
.isEmpty() return true if String length is 0.

Strings are objects. Object instances (the value behind them) have to be compared manually with a method to assure that the content is the same.
The == operator just compares the string references ("adresses"). So when you create 2 object instances at runtime, they have different adresses even if the content is the same. Compile-time strings on the other hand are internalized, they are put into special memory and duplicates are sorted out.
System.out.println(new String("test") == new String("test"));
This will print false, because those 2 objects get created at runtime. The new keyword in the first example mandates that a new object with a new adress is created.
System.out.println("test" == "test");
This will print true, because they are String literals, which are known at runtime, you are not explicitly stating the new keyword here either. You are simply specifying that you want those literals represented in the code somehow, so the compiler internalizes them.

Related

Can anyone suggest me that below if condition is wrong or not? [duplicate]

This question already has answers here:
Check whether a String is not Null and not Empty
(35 answers)
Closed 6 years ago.
May occur any exception in coding for checking string is null or not ? Please help.
String code ;
if (!code.equals(null)) {
}
else
{
}
Here is how you can check if String value is null or not
if(code != null){
}else{
}
You can not us !code.equals(null) because, equals is used to compare same object type. null is not any object type and code is String. If you consider null as String, then you can use !code.equals("null")
String can be checked like this:
if(code.equals("null") || code.equals("")) {
// code to do when string is null.
}
else {
// code to do when string is not null.
}
equals() is use to check the similarity of two String, and == or != is use to check the condition. In your case you are checking the similarity of string.
if (!code.equals(null)) {
//code checks that String code is equal to null or not
}
else
{
}
another
if (code != null) {
//code checks if code is not equals to null (condition checking)
}
else
{
}
There are many ways to check if String is empty in Java, but what is the right way of doing it? right in the sense of robustness, performance and readability. If robustness is your priority then using equals() method or Apache commons StringUtils is the right way to do this check. If you don't want to use third party library and happy of doing null check by yourself, then checking String's length is the fastest way and using isEmpty() method from String is most readable way. By the way, don't confuse between empty and null String, if your application treat them same, then you can consider them same otherwise they are different, as null may not be classified as empty. Here are three examples of checking String is empty or not by using JDK library itself.
Read more Here
You can't use .equals(null) to make a null check, because the API description for Object#equals states that:
For any non-null reference value x, x.equals(null) should return false.
Not only would this be a useless check (since it always returns false), it would also throw a NullPointerException if code actually was null, because a null value does not define an equals method.
Object x = null;
boolean isNull = x.equals(null); // NullPointerException on .equals
The only practical way to do a null check is to use:
if (code != null) {
}
If you want to check whether string is empty i.e. null or "" then use
if(TextUtils.isEmpty(code)){
}else{
}
equals checks the value exists in string.

Android JSONObject getString method check for null/NULL?

Hitting a brick wall in my code at the moment for fetching json objects from multiple pages(using a loop) in a AsyncTask. It reaches the last page, but getting the correct if statement to ensure that the loop DOESN'T run again and continues on is baffling me.
String data = //some correct json data with next element that holds a uri parseable string
JSONObject initial = new JSONObject(data);
String next = initial.getString(nextObjSTR);
//gonna start from the "last" page and recursively return to the 1st page
if(*The if condition I need help with*) {
//there is another page
makeConnection(Uri.parse(next));
}
Basically, the last page of json elements has a next element with a null or no element value, which triggers the IOException error caught in makeConnection method because my initial if statement has always been failing.
Can I get a reason or help as to the appropriate if check for Strings from json? I've tried String != null as NullPointerExceptions occur if I use any method from String to compare. Likewise, JsonObject.NULL comparison doesn't work for me either.
None of the other answers worked, and I ended up questioning whether the element was really null despite looking at the parsed json data via an online tool. In the end, JSONObject.IsNull(element mapping name) is the right approach.
If you're sure that the value is either null (empty) or a correct URI, and assuming that the nextObjSTR key is always present in the data JSON, then that will do:
if (next != null && !next.trim().isEmpty()) {
makeConnection(Uri.parse(next));
}
Or, since you're on Android, it's better use the more convenient method:
if (!TextUtils.isEmpty(next)) {
makeConnection(Uri.parse(next));
}
You can use the optString Method of the JSONObject. If the JSON key is not this method will return a empty string, so you can check it easily:
String next = initial.optString(nextObjSTR);
if ( ! next.isEmpty() ) {
makeConnection(Uri.parse(next));
}
Source: https://developer.android.com/reference/org/json/JSONObject.html#optString(java.lang.String)
you must check value with key is has in json object.
Try below code:
JSONObject initial = new JSONObject(data);
if(initial.has(nextObjSTR)) {
String next = initial.getString(nextObjSTR);
if (next != null && !next.isEmpty()) {
makeConnection(Uri.parse(next));
}
}
I do like this...
String value;
if(jsonObject.get("name").toString.equals("null")){
value = "";
else{
value = jsonObject.getString("name");
}

"==" for Strings always returning false [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I can't seem to get the code within the second if statement to execute. I have logged both values being compared and also ran the debugger and checked them. They are both "a". It always shows the incorrectPasswordDialog. This question seems difficult because it seems as though it should just work but any help is appreciated.
private void logUserIn(AppUser user) {
if (user != null){
Log.d("mPassword: ", mPassword);
Log.d("user.getPassword(): ", user.getPassword());
String userPassword = user.getPassword().toString();
String formPassword = mPassword.toString();
if ( userPassword == formPassword ){
Intent welcomePage = new Intent(this, StartScreenActivity.class);
welcomePage.putExtra("name", mName);
startActivity(welcomePage);
}
else {
showIncorrectPasswordDialog();
}
}else {
showIncorrectUserNameDialog();
}
}
You are comparing the object identity. Use string.equals() to check for equivalence.
if(userPassword.equals(formPassword)){
}
Change
if ( userPassword == formPassword ){
to
if ( userPassword.equals(formPassword) ){
== compares object references, whereas .equals compared String values.
You can not compare string using ==
try like this
Compares the specified object to this string and returns true if they are equal. The object must be an instance of string with the same characters in the same order.
if ( userPassword.equals(formPassword)){
// do some stuff
}
or
Compares the specified string to this string ignoring the case of the characters and returns true if they are equal.
if(userPassword.equalsIgnoreCase(formPassword))
{
//do some stuff
}
In JAVA to compare between strings, you should use:
if(userPassword.equals(formPassword)) {
// they are equal
}
Change
if ( userPassword == formPassword ){
to
if ( userPassword.equals(formPassword)){
In Java, String comparison is done with .equals(). Using == compares the object reference and not their values.
Java String comparison
In JAVA you should use equals to judge equal of value of different String.
== is used to judge object pointer for string, so it would only return false in your case.

integer value comparison not working properly

I've a string value String str="Success"
How to check the "str" value is not equal to "Success". If I try if(str!="Success"). It is not working properly.
I've a integer value int a=250 If I use If(a!=250) this is also not working properly.
How to code for these conditional statements ? I'm using Android and Eclipse version 2.1.
Any help would be appreciable.
a!=250 should work.
For string try str.equals("Success")
As every one said, String values should compare with .equals method.
like
if(str.equals("Success"))
{
System.out.println("My String is Success");
}
Next coming to integer comparison.
As you have said, you have the integer value
int a=250
if(a!=250)
{
// Some code
}
Here already your a value is 250. then you are executing some lines of code if a value is not equal to 250. Then how the condition will execute. if you want to test then
change the a value and then check again as
int a=50
if(a!=250)
{
// Some code===============> Now this code will execute
}
For string comparison, use the standard String.equals() method.
str.equals("Success"); - For Equals
if(!str.equals("Success")) - For Not Equals(your case)
And for int, what is being used, is proper. a!=250 will return false in your case. Hence, it'll not enter the if block.
You should try to study Java first ;)
This is not the way to do a String comparison. For String comparison, you must use .equals(String) method.
String str1 = "str1";
String str2 = "str2";
if(str1.equals(str2)) {
//do something
}
You should not compare strings with != or =. That won't work in most cases.
new String("test").equals("test")
Should be used for comparison.
!= compares the value and is true if they are NOT equal.
you could also use something like if(a == 250){...}
In Java you cannot use == to compare Strings, you must use:
if(string.equals("example"))
So let's use equals() in your conditional and optimize it:
if(!str.equals("Success"))
this will work

Android text string comparison

In a custom SimpleCursorAdapter, I'm trying to compare a status String, with confusing results.
My string is initialised from the cursor like this (and I've checked with toast that it contains the expected values).
String visitStatus = cursor.getString(cursor.getColumnIndex(CallData.COLUMN_VisitStatus));
visitStatus can be null, Open, Cancelled or Complete.
If I try to compare visitStatus to "any string in quotes", the app crashes with a NullPointerException. Only if I compare to null do I get anything at all - and that is no use to me
if(visitStatus.equals(null)) // the app crashes with a NullPointerException
if(visitStatus == null) // doesn't crash
if(visitStatus != null) // doesn't crash
if(visitStatus == "Complete") // doesn't crash or do anything
if(visitStatus.equals("Complete")) // the app crashes with a NullPointerException.
Basically, I can compare to null, but only in the way that isn't supposed to work. I can't compare to actual strings such as "Open" or "Complete".
I'm going slightly nuts with this, and am badly missing my C# comfort zone. This particular activity is a nightmare of listfragments, contentproviders, customadapters, viewpagers, pagertitlestrips and list row xml templates!
halp!
This is because visitStatus is null. Whenever you try to access its methods, it crashes. (That is: visitString.equals(), visitString.length(), etc., all will crash.)
However, the equality operator (==) supports null parameters on either side of it. (So, if (null == null) is a valid check.)
You should check like this:
if (visitStatus != null && visitStatus.equals("Complete")) {
// ...
}
Or, you can do "Yoda syntax" (backwards checking), which supports null parameters:
if ("Complete".equals(visitStatus)) {
// ...
}
Also, a final note: You cannot compare string contents using == (as in, you cannot do "a" == new String("a"), nor visitString == "Complete"). For a detailed explanation on that, see this Q&A thread.
String should be compared using .equals()
The NullPointerException caused because the visitStatus is null

Categories

Resources