editText box not working properly. Android

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 07:13:23

问题


I'm trying to get values out of edittext boxes and on the click of a button, I want to compare if the text inside the edittext box matches a certain value. If it does, a new intent should be called. If it doesn't it should show an error. Here is my code after the button is clicked...

     if(v.getId() == R.id.button1){

        id = et1.getText().toString();
        Toast toast = Toast.makeText(this, "Value of id is: " + id, Toast.LENGTH_SHORT);
        toast.show();

        if(id == "abc"){
            Intent i= new Intent(Slogin.this, Sales.class);
            startActivity(i);
        }else{
            Toast toast = Toast.makeText(this, "Wrong id pass",                                                                            Toast.LENGTH_SHORT);
            toast.show();
        }

Now the problem is that even when I enter "abc" (without the double commas), it still shows me the error "Wrong id pass". While the Toast clearly shows that I have entered abd and the string id now holds the value "abc". Help required...


回答1:


Try this.. if id is int use like this id == 5. but id is String you should use id.equals("abc")

if(id.equals("abc")){           //Correction is here
            Intent i= new Intent(Slogin.this, Sales.class);
            startActivity(i);
        }else{
            Toast toast = Toast.makeText(this, "Wrong id pass",                                                                            Toast.LENGTH_SHORT);
            toast.show();
        }

== always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.

However, the equals method can be overridden - so two distinct objects can still be equal......




回答2:


Use

if(id.equals("abc"))

instead Of

 if(id == "abc")


来源:https://stackoverflow.com/questions/20095073/edittext-box-not-working-properly-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!