簡體   English   中英

無法使用Retrofit2 + RxJava2在回收器視圖中獲取數據

[英]Unable to fetch data in recycler view using Retrofit2 + RxJava2

我正在使用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() {

                }
            });
      }

}

有人請讓我知道為什么不顯示數據是什么問題,我們將不勝感激。

謝謝

我猜您正在嘗試從另一個線程使用回收器視圖及其適配器。 只需嘗試在subscribeOn(Schedulers.io())之后在Rx鏈中添加方法observeOn(AndroidSchedulers.mainThread())

另外,從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

希望能幫助到你!

代替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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM