-
[TIP] String 빈문자열/null 검사하기Android 2016. 5. 26. 14:03
자바에서 String 변수를 사용하기 전에 미리 변수의 상태가 null 또는 "" (빈 문자열) 인지 검사를 해야 할 필요가 있다.
지금까지는
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersString stringVal = null; if (stringVal == null || stringVal.equals("")) { return; } 이런식으로 null 검사와 빈 문자열 검사까지 해주고 있었다.
그러나 이런식으로 검사를 하면 equel("")에서 String 빈 객체를 생성하게 되는 걸 알게 됐다.
찾아본 결과 TextUtils 클래스를 사용하면 좋다고 한다.
TextUtils에 isEmpty 메서드를 사용하면 되는 데 사용법은 다음과 같다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersString stringVal = null; if (TextUtils.isEmpty(stringVal)) { return; } isEmpty 메서드의 내부를 살펴보면
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters/** * 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; } 이렇게 생겼는데 CharSequence를 전달받아 null 검사와 길이 검사까지 해준다.
전달받은 값이 null이거나 길이가 0이면 ( "" 이면 ) true를 반환하고
아니면 false를 반환하는 메서드이다.
'Android' 카테고리의 다른 글
[Proguard] 라이브러리 룰 모음집 (0) 2016.11.04 [Glide] 3. Image Resize (2) 2016.09.23 [Glide] 2. Glide의 여러가지 기능들 (0) 2016.09.19 [Glide] 1. 이미지 라이브러리 Glide (0) 2016.09.13 [TIP] viewpager에서 현재 보여지는 페이지 알아내기 (0) 2016.07.05