无法使用Retrofit2 + RxJava2在回收器视图中获取数据

时间:2019-07-17 11:47:02

标签: android retrofit2 rx-java2

我正在使用Retrofit2发出网络请求,我试图使用RxJava实现从回收器视图中的服务器获取数据,尽管我在onNext()方法上显示了Log消息,但数据却未获取。

下面是我的代码:

ApiService.java

public interface ApiService {

    @POST("retrofitUsers")
    @FormUrlEncoded
    Observable<String> saveData(@Field("name") String name,
                             @Field("age") String age)

    @GET("getUsers")
    Flowable<List<BioData>> getData();

}

RetrofitClient.java

public class RetrofitClient {

    private static Retrofit retrofit = null;

    public static Retrofit getInstance() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(22,TimeUnit.SECONDS)
            .readTimeout(22, TimeUnit.SECONDS)
            .connectTimeout(22, TimeUnit.SECONDS)
            .build();

        if(retrofit == null)
            retrofit = new Retrofit.Builder()
                .baseUrl("https://example.com/")
                .addConverterFactory(
                    GsonConverterFactory
                        .create(
                            new GsonBuilder().setLenient().create()
                        )
                )
                .addCallAdapterFactory(
                    RxJava2CallAdapterFactory.create()
                )
                .client(okHttpClient)
                .build();

        return retrofit;
    }

    private RetrofitClient() {
    }
}

BioData.java

public class BioData {

    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("age")
    @Expose
    private String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

Users.java

public class Users extends AppCompatActivity {

    RecyclerView recycle;
    UserAdapter adapter;
    ProgressBar prog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_users);

        prog = findViewById(R.id.prog);

        recycle = findViewById(R.id.recycle);
        recycle.setHasFixedSize(true);
        recycle.setLayoutManager(new LinearLayoutManager(this));

        fetchData();
     }

     private void fetchData() {

         Retrofit retrofit  = RetrofitClient.getInstance();
         ApiService myApi = retrofit.create(ApiService.class);

         myApi.getData()
             .toObservable()
             .subscribeOn(Schedulers.io())
             .subscribe(new Observer<List<BioData>>() {

                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(List<BioData> bioData) {

                    if(bioData.size() > 0){
                        Log.d("Data","Hello");
                    }
                    adapter = new UserAdapter(bioData,getApplicationContext());
                    recycle.setAdapter(adapter);
                }

                @Override
                public void onError(Throwable e) {

                    Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onComplete() {

                }
            });
      }

}

请让我知道为什么不显示数据的问题是什么。我们将不胜感激。

谢谢

2 个答案:

答案 0 :(得分:1)

我猜您正在尝试从另一个线程使用回收站视图及其适配器。只需尝试在observeOn(AndroidSchedulers.mainThread())

之后的Rx链中添加方法subscribeOn(Schedulers.io())

此外,从onNext()中删除以下几行:

adapter = new UserAdapter(bioData, getApplicationContext());
recycle.setAdapter(adapter);

请先(在初始化回收站视图时)初始化适配器,然后在适配器空列表内传递,然后将此先前初始化的适配器设置为回收站视图。然后,在onNext()内,从服务器到适配器设置获取的列表,然后调用adapter.notifyDataSetChanged()

您可以在下面看到的代码示例:

adapter = new UserAdapter(new ArrayList<BioData>(), getApplicationContext());

recycle = findViewById(R.id.recycle);
recycle.setHasFixedSize(true);
recycle.setLayoutManager(new LinearLayoutManager(this));

recycle.setAdapter(adapter);
...

然后onNext()

if(bioData.size() > 0){
    Log.d("Data","Hello");
}
adapter.setData(bioData, getApplicationContext());
adapter.notifyDataSetChanged();

当然,您需要在setData(List<BioData>)中声明UserAdapter方法。

希望有帮助!

答案 1 :(得分:0)

代替OnNext,尝试实现以下方法

private void loadJSON() {

    RequestInterface requestInterface = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build().create(RequestInterface.class);

    mCompositeDisposable.add(requestInterface.register()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(this::handleResponse,this::handleError));
}

private void handleResponse(List<Android> androidList) {

    mAndroidArrayList = new ArrayList<>(androidList);
    mAdapter = new DataAdapter(mAndroidArrayList);
    mRecyclerView.setAdapter(mAdapter);
}

请检查以下链接 https://www.learn2crack.com/2016/11/android-rxjava-2-and-retrofit.html