2016-11-03 5 views
1

뉴스 목록이 있습니다. 모든 뉴스에는 작성자 ID가 있습니다. 저자 ID를 뉴스에서 가져와 작성자에게 전화하여 이름을 가져오고 각 뉴스에 작성자 이름을 설정해야합니다.목록의 각 항목에 대한 Null 값 확인

보기 쉽고 작동하지만 일부 작성자 이름이 null이며 앱이 exepcion을 발생시킵니다. 따라서 작성자 이름이 null 인 경우 뉴스리스트의 각 항목을 확인해야하며이를 "알 수 없음"문자열로 바꿉니다. 내 변형이 작동하지 않습니다.

.flatMap(new Func1<News, Observable<News>>() { 
     @Override 
     public Observable<News> call(News news) { 
      return apiService.getAuthor(news.getId()) 
        .doOnNext(new Action1<Author>() { 
         @Override 
         public void call(Author author) { 

          if (!author.getName().equals("null")) { 
           news.setAuthorName(author.getName()); 
          } else { 
           news.setAuthorName("Unknown"); 
          } 
         } 
        }) 
        .observeOn(Schedulers.io()) 
        .map(new Func1<Author, News>() { 
         @Override 
         public News call(Author author) { 
          return news; 
         } 
        }) 
        .subscribeOn(Schedulers.newThread()); 
     } 
    }) 

답변

1

여기에는 null 확인을 돕기위한 몇 가지 일반적인 유틸리티 기능이 있습니다. 이것들을 Utils 클래스 나 다른 것에 추가하십시오. 또한 문자열 널 (null) 검사,

private static final String EMPTY = ""; 
private static final String NULL = "null"; 

/** 
* Method checks if String value is empty 
* 
* @param str 
* @return string 
*/ 
public static boolean isStringEmpty(String str) { 
    return str == null || str.length() == 0 || EMPTY.equals(str.trim()) || NULL.equals(str); 
} 

/** 
* Method is used to check if objects are null 
* 
* @param objectToCheck 
* @param <T> 
* @return true if objectToCheck is null 
*/ 
public static <T> boolean checkIfNull(T objectToCheck) { 
    return objectToCheck == null; 
} 

지금 코드를 업데이트 객체 널 (null)

검사보다 다른 것을 알 수

.flatMap(new Func1<News, Observable<News>>() { 
     @Override 
     public Observable<News> call(News news) { 
      return apiService.getAuthor(news.getId()) 
        .doOnNext(new Action1<Author>() { 
         @Override 
         public void call(Author author) { 
          // notice how I first confirm that the object is not null 
          // and then I check if the String value from the object is not null 
          if (!Utils.checkIfNull(author) && !Utils.isStringEmpty(author.getName()) { 
           news.setAuthorName(author.getName()); 
          } else { 
           news.setAuthorName("Unknown"); 
          } 


         } 
        }) 
        .observeOn(Schedulers.io()) 
        .map(new Func1<Author, News>() { 
         @Override 
         public News call(Author author) { 
          return news; 
         } 
        }) 
        .subscribeOn(Schedulers.newThread()); 
     } 
    }) 

리터럴 문자열을 검사하기 때문에이 문제가되어 발생하는 이유는, 「null」는, String가 null는 아니지 않은 것을 나타냅니다.

+0

오 진짜 어리석은 실수지만, 어쨌든. – STK90

관련 문제