2016-11-03 51 views
1

我有新闻列表。每个新闻都有作者ID,我需要从新闻中获取作者ID,然后致电作者取他的名字并为每个新闻设置作者的名字。检查列表中每个项目的空值

看起来很简单,它可以工作,但一些作者的名字是空的,app会抛出一个exepcion。因此,如果作者的姓名为空,我需要检查newslist中的每个项目,将其替换为“未知”字符串。我的变体不起作用。

.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

下面是一些常见的实用功能,可以帮助您进行空检查。将这些添加到Utils类或其他东西。还要注意,检查字符串空值,是不同于检查对象空

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; 
} 

现在更新代码

.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”不一定是该字符串为空。

+0

哦真是愚蠢的错误,但无论如何感谢。 – STK90

相关问题