我的代碼如下所示。
APIInterface.java
public interface APIService {
@GET("/bins/tdze5")
Observable<List<Student>> getdata();
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<Student> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
getData();
}
private void getData() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.myjson.com")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
APIService apiService = retrofit.create(APIService.class);
Observable<List<Student>> observable = apiService.getdata().subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
observable.subscribe(new Observer<List<Student>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.d("error",e.toString());
}
@Override
public void onNext(List<Student> students) {
list = new ArrayList<>();
Log.d("response size", String.valueOf(students.size()));
for(int i = 0; i < students.size(); i++){
Student student = new Student();
student.setId(students.get(i).getId());
student.setName(students.get(i).getName());
list.add(student);
}
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(list);
RecyclerView.LayoutManager recyce = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(recyce);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(recyclerAdapter);
}
});
}
}
我的模型類是如下
Student.java
public class Student {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} }
我越來越
D/error: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ in Log
我已經找遍這個錯誤,但我找不到任何關於RxJava和改造任何東西。
它只是你的反應是一個對象,但你想獲取的排列U可以發表你的JSON響應 – Anil
它期望一個數組,你給它一個對象。你的模型類的主要問題。你沒有正確解析它。你可以在這裏發佈你的迴應,你從服務器得到什麼迴應? – shahid17june
感謝您的幫助 – Abhijeet