PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, April 27, 2022

[FIXED] Why there is 'NullPointerException' warning when I already use !TextUtils.isEmpty()?

 April 27, 2022     android, warnings     No comments   

Issue

I am using following code:

Editable editable = popupSearchETHP.getText();

if (!TextUtils.isEmpty(editable)) {
      final String fieldVal = editable.toString();
}

and

final String fieldVal = editable.toString();

this statement produces warning:

Method invocation 'toString' may produce 'NullPointerException'

Why???? I am already checking if it is empty or not. But it still produces warning. If you look at source code of TextUtils.isEmpty() then you will find that:

 /**
 * Returns true if the string is null or 0-length.
 * @param str the string to be examined
 * @return true if str is null or zero length
 */
public static boolean isEmpty(@Nullable CharSequence str) {
    return str == null || str.length() == 0;
}

it already checks for null and it also checks its length and then returns result. So why there is warning Method invocation 'toString' may produce 'NullPointerException'?


Solution

I don't know why there is warning when using !TextUtils.isEmpty() but I crafted my custom function which will work similarly and will not produce any warning:

private boolean isNotEmpty(CharSequence str) {
        return (str!=null && str.length() > 0);
    }

//Use this like below
if(isNotEmpty(editable))
{ }

You can also instead use

//noinspection ConstantConditions

if you need to remove the warning only on a specific line.



Answered By - Chaitanya Karmarkar
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing