我尝试使用Retrofit从服务器向Spinner添加动态数据。数据出来了。但我得到了错误。 Logcat说:
致命的例外:主要 处理:com.example.syaifulhusein.paketku,PID:31246 java.lang.NullPointerException:尝试调用接口方法' int java.util.List.size()'在空对象引用上
这是我的函数 initSpinnerKotaAsal 代码
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.1" />
<DotNetCliToolReference Include="BundlerMinifier.Core" Version="2.5.357" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.1" />
这是我的回复对象
private void initSpinnerKotaAsal() {
loading = ProgressDialog.show(mContext, null, "harap tunggu...", true, false);
mApiService.getProvince(API_KEY).enqueue(new Callback<Rajaongkir>() {
@Override
public void onResponse(Call<Rajaongkir> call, Response<Rajaongkir> response) {
if (response.isSuccessful()) {
loading.dismiss();
List<ResultsItem> resultsItems = response.body().getResults();
List<String> listSpinner = new ArrayList<String>();
for (int i = 0; i < resultsItems.size(); i++) {
listSpinner.add(resultsItems.get(i).getProvince());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext,
android.R.layout.simple_spinner_item, listSpinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerKotaAsal.setAdapter(adapter);
}
else {
loading.dismiss();
Toast.makeText(mContext, "Gagal", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<Rajaongkir> call, Throwable t) {
}
});
}
这是我的 ResultsItem.java
package com.example.syaifulhusein.paketku.model;
import java.util.List;
import com.google.gson.annotations.SerializedName;
public class Rajaongkir{
@SerializedName("query")
private List<Object> query;
@SerializedName("results")
private List<ResultsItem> results;
@SerializedName("status")
private Status status;
public void setQuery(List<Object> query){
this.query = query;
}
public List<Object> getQuery(){
return query;
}
public void setResults(List<ResultsItem> results){
this.results = results;
}
public List<ResultsItem> getResults(){
return results;
}
public void setStatus(Status status){
this.status = status;
}
public Status getStatus(){
return status;
}
@Override
public String toString(){
return
"Rajaongkir{" +
"query = '" + query + '\'' +
",results = '" + results + '\'' +
",status = '" + status + '\'' +
"}";
}
}
答案 0 :(得分:1)
使用GsonFormate
插件在Android Studio中创建正确的Pojo模型。