Fragment中RecyclerView不显示问题排查(数据已成功加载)
我仔细梳理了你的Fragment、Adapter和布局代码,找到了几个导致RecyclerView不显示数据的核心问题,下面是逐一的修复方案:
1. 移除ScrollView嵌套RecyclerView的布局问题
你把RecyclerView放在了ScrollView里面,这是Android开发里的常见误区——ScrollView会干扰RecyclerView的高度计算,导致它无法正确渲染内容(因为RecyclerView无法确定自己的实际高度,会被ScrollView压缩成不可见的状态)。
修改fragment_home.xml:
直接去掉ScrollView和外层的LinearLayout,让RecyclerView占满整个Fragment:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.anjana.decorightkitchen.fragment.HomeFragment"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerViewNotifications" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout>
2. 数据更新后必须通知适配器
在fetchNotifications的onResponse回调里,你已经把服务器返回的通知数据添加到了listNotifications,但没有告诉适配器数据已经更新,所以RecyclerView根本不知道要刷新UI。
修复fetchNotifications的onResponse方法:
@Override public void onResponse(String response) { Log.d("d", "getting response.........\n" + response); List<Notifications> notiList = Arrays.asList(gson.fromJson(response, Notifications[].class)); listNotifications.addAll(notiList); // 关键:通知适配器数据发生变化,触发UI刷新 notificationsRecyclerAdapter.notifyDataSetChanged(); }
3. 修复重复请求与列表清空的逻辑错误
在onViewCreated里,你先是判断网络状态调用了一次fetchNotifications,之后又重复调用了一次,还提前执行了listNotifications.clear()——这会把第一次请求回来的数据直接清空,同时重复请求也会浪费网络资源。
清理onViewCreated中的冗余代码:
删除这段多余的代码:
// 删除以下代码块 listNotifications.clear(); try { fetchNotifications(loggedUserId); // listNotifications.addAll(); }catch (NullPointerException e){ Log.d("sdfs", "No Data available"); } notificationsRecyclerAdapter.notifyDataSetChanged();
4. 避免局部变量覆盖成员变量
在onViewCreated中,你定义了一个局部的loggedUserId变量,覆盖了类的成员变量,虽然当前代码里局部变量能正常使用,但很容易在后续维护中引发空指针问题,建议直接赋值给成员变量:
// 原代码 // String loggedUserId = user.get(SessionManagement.KEY_USERID); // 修改为 this.loggedUserId = user.get(SessionManagement.KEY_USERID);
5. 清理Adapter中的无用代码
在NotificationsRecyclerAdapter的onBindViewHolder里,你创建了一个空的Notifications对象并打印它的属性,这不仅没用,还会输出null日志,建议删掉:
// 删除以下无用代码 Notifications noti=new Notifications(); Log.d("NotificationsAdapter : ", "type : " + noti.getAction()); Log.d("NotificationsAdapter : ", "status : " + noti.getCreateddate());
做完这些修改后,你的RecyclerView应该就能正常加载并显示服务器返回的通知数据了。
内容的提问来源于stack exchange,提问作者anj kri




