开发者

How to restrict this function from execution in android? Please help

This code is present in one of this activity. I want to restrict addJoke() function from executing if the String variable new_joke is null, has no text or contains just spaces. Here is code

protected void initAddJokeListeners() {
    // TODO
    m_vwJokeButton.setOnClickListener(new OnClickListener() {
        @Override
    public void onClick(View view) {
    //Implement code to add a new joke here...
            String new_joke=m_vwJokeEditText.getText().toString();
            if(new_joke!=null&&new_joke!=""&&new_joke!=" ")
            {
                addJoke(new_joke);
            }
        }
    });
}

I don't know why addJoke() function is getting exe开发者_开发百科cuted even I don't enter any text in EditText field. Please help.


you must do the String comparison with String's .equals(), so:

protected void initAddJokeListeners() {
    // TODO
    m_vwJokeButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            //Implement code to add a new joke here...
            String new_joke = m_vwJokeEditText.getText().toString().trim();
            if(!new_joke.equals("")) {
                addJoke(new_joke);
            }
        }
    });
}


You should use:

if (new_joke != null && !new_joke.trim().equals(""))

although in this case, you can leave the new_joke == null as that will never happen.

This is because with new_joke == "" you create a new empty string object and check whether that object is the same object as new_joke which is not the case.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜