我从responseObject
和rootObject
列表中获得了一个列表。 responseObject
列表中填充了新项目(包含标题,ID,摘要等的对象),我想将它们添加到我的rootObject
列表中,但是我收到错误:
java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
两个列表都是命名结果。有谁知道如何将这些项目添加到我的rootObject
这是代码:
public void success(RootObject responseObject, Response response) {
rootObject.nextId = responseObject.nextId;
rootObject.results.add(responseObject.results.get(0));
}
我检查了回复,responseObject
结果中有项目
整个代码:
public class NewsController {
private RestAdapter restAdapter;
public RootObject rootObject = new RootObject();
public MainActivity ma;
static final String API_URL = "http://SECRETAPILINK.SECRET/api";
public void getNews(){
OkHttpClient mOkHttpClient = new OkHttpClient();
mOkHttpClient.setConnectTimeout(15000,TimeUnit.MILLISECONDS);
mOkHttpClient.setReadTimeout(15000, TimeUnit.MILLISECONDS);
restAdapter = new RestAdapter.Builder().setEndpoint(API_URL).setClient(new OkClient(mOkHttpClient)).setLogLevel(RestAdapter.LogLevel.FULL) .build();
GetNewsService service = restAdapter.create(GetNewsService.class);
Callback<RootObject> cb = new Callback<RootObject>() {
@Override
public void success(RootObject responseObject, Response response) {
Log.v("AASSAASS", responseObject.results.get(0).Title);
rootObject.nextId = responseObject.nextId;
rootObject.results.addAll(responseObject.results);
Log.v("AASSAASS", responseObject.results.get(0).Title);
}
@Override
public void failure(RetrofitError error) {
Log.v("AASSAA", error.toString());
}
};
service.GetNewsItems(cb);
}
}
答案 0 :(得分:1)
你还没有初始化rootObject.results
arrayList,这就是它抛出NPE的原因。
为了解释,让我们看一个小例子
class Ideone
{
List<Integer> list;
public static void main (String[] args) throws java.lang.Exception
{
try {
Ideone id = new Ideone();
id.list = new ArrayList<Integer>();
id.list.add(1);
id.list.add(2);
Ideone copyId = new Ideone();
copyId.list = new ArrayList<Integer>();
copyId.list.addAll(id.list);
Ideone npeId = new Ideone();
npeId.list.add(id.list); //->nullpointerexception
} catch (NullPointerException e) {
System.out.println(e);
}
}
}
在上面的例子中,如果你没有初始化npeId
,它将会抛出一个NPE。
在您的代码中,您需要类似
的内容rootObject.results = new ArrayList<...>();