开发者

problem in comparing two Strings in android

开发者 https://www.devze.com 2023-03-10 23:19 出处:网络
in my app i have two editbox in which the user types the email and password. The values are send to an URL and if the return values is success i am moving to a new activity, else if the return value i

in my app i have two editbox in which the user types the email and password. The values are send to an URL and if the return values is success i am moving to a new activity, else if the return value is Email And Password Not Match! i want to show an alert box that emailand pwd mismatches.

For this, after getting the xml file from the network using sax parser i am doing parsing the and if the return value is "Email And Password Not Match!", i am storing this in a constant names as ERROR_VALUE.

i have already stored the value in a String constant as follows

public static String ERROR_CONST   = "Email And Password Not Match!";

now i am comparing those values and showing an alert box,

if (ERROR_CONST.contentEquals(ERROR_VALUE))
  {
       alertbox();
  }

after this i am using the else part to move to a new activity, my app gets crashed at this part only

else if(ERROR_VALUE == null)
{
  Intent myIntent = new Intent(getBaseContext开发者_C百科(), Add.class);
  startActivityForResult(myIntent, 0);
  finish();
}
                }

how to use else condition successfully in my app, please help me friends


Well when comparing 2 strings its always a good idea to use

s1.compareToIgnoreCase(s2);

reading your post I would suggest you use enum or constants

public static final ERROR_CODE_INVALIDE_LOGGIN = 1;

to compare rather that strings.

Comparing strings is tedious (have to be careful that your comparing the characters and not references etc.). As comparing 2 int is easy and takes less time


I checked quickly in the javaDoc

contentEquals compares your String to a StringBuffer

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#contentEquals(java.lang.StringBuffer)

as

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#compareTo(java.lang.String)

Compares the actual string letters


other edit (sorry about that)

if your code is

if (ERROR_CONST.contentEquals(ERROR_VALUE))
  {
       alertbox();
  }


else if(ERROR_VALUE == null)
{
  Intent myIntent = new Intent(getBaseContext(), Add.class);
  startActivityForResult(myIntent, 0);
  finish();
}

then you have a problem when ERROR_VALUE is == null.

you pass null in contentequals and I'm guessing Java tries to convert null to StringBuffer and crashes.

what you want to do it

if(ERROR_VALUE == null)
    {
      Intent myIntent = new Intent(getBaseContext(), Add.class);
      startActivityForResult(myIntent, 0);
      finish();
    }else if (ERROR_CONST. equalsIgnoreCase(ERROR_VALUE))
    {
       alertbox();
    }

this way you avoid any null pointer exceptions and your compare will work just fine

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号