如何在 RecyclerView 中显示不同的数据集取决于用户互联网连接?

How to display different set of data in RecyclerView depends on user internet connectivity?

我有一个 RecyclerView 当用户连接到 Internet 时,我的应用程序将使用 Volley 获取 Json 并显示到 RecyclerView。同时届时,获取的 Json 也将存储在 Realm 数据库中。

这在用户连接到 Internet.So 时效果很好现在的主要问题是,当用户离线时,我无法向远程服务器发出请求,因此我需要在 Realm 中显示数据数据库,自上次 volley request.

以来存储了哪些数据

这就是我到目前为止设置适配器的方式,以显示来自 Volley Request

的项目
List<FeedItem>items = new ArrayList<>();

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState)

        adapter = new adapter(this,items);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(adapter);

到目前为止我尝试了什么,

为了让我知道网络是否存在,我做了以下检查

ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null&& activeNetwork.isConnectedOrConnecting();

//check for network
if(isConnected){
  //a different arraylist(),or different adapter here?
}else{

}

所以我卡在这里,我不知道我是否应该向适配器添加不同的 Arraylist(),或者必须制作完全不同的适配器来显示 Realm database.[=25 中的数据=]

有一件事我也想确定一下,我在没有从 Realm 获取数据的情况下在飞行模式下测试我的应用程序,之前获取的数据仍然显示,是否 RecycleView 会自动缓存数据,所以我不需要 Realm database 离线?

那么如何解决这个问题呢?

当你想维护两个支持(online/offline)是你的应用程序时,最好的方法不是检查互联网连接,而是在所有情况下让 volley 请求,如果你得到响应简单显示在你的 recycler view 并插入到您的 local database 中,但是如果您遇到任何类型的错误,(没有互联网、一些服务器错误、一些其他问题)只需获取离线可用的数据。 由于来自服务器和离线的数据相同,例如Contact。在所有情况下,您都可以将其添加到同一列表中。

您的数据类型相同,因此使用具有相同 Adapter 的不同 Arraylist。