Android ViewModel在观察时删除我的所有数据

qrjkbowd  于 2023-02-20  发布在  Android
关注(0)|答案(1)|浏览(184)

我正在使用Android Studio开发一个应用程序,我希望在RecyclerView的同时使用MutableLiveData。问题是,当我向MutableLiveData添加一个新项目时,它会更新,然后返回到上一个片段,该项目会由于某种未知原因而被删除。FirstFragment.javaonCreateView方法的代码:

@Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        binding = FragmentFirstBinding.inflate(inflater, container, false);

        notificationsViewModel = new ViewModelProvider(requireActivity()).get(NotificationsViewModel.class);

        // Binding recycler views
        // Notifications

        RecyclerView rvNotification = binding.registeredNotification;

        Log.d("NA", "New Adapter");
        NotificationAdapter adapter = new NotificationAdapter();

        Log.d("NA", "Setting adapter");
        rvNotification.setAdapter(adapter);

        Log.d("NA", "Setting layout");
        rvNotification.setLayoutManager(new LinearLayoutManager(getActivity()));

        Log.d("NA", "Getting the MLD");
        MutableLiveData<List<NotificationContent>> notifs = notificationsViewModel.getNotifications();

        Log.d("NA", "Adding observer");
        notifs.observe(requireActivity(), new Observer<List<NotificationContent>>() {
            @Override
            public void onChanged(List<NotificationContent> notificationContents) {
                Log.d("ANDROIDAPP", String.format("onChanged: detected and done, item size %d", notificationContents.size()));
                adapter.updateNotifications(notificationContents);
            }
        });

        return binding.getRoot();
    }

ViewModel实现的代码:

public class NotificationsViewModel  extends ViewModel {
    private final MutableLiveData<List<NotificationContent>> notifications = new MutableLiveData<List<NotificationContent>>();

    public MutableLiveData<List<NotificationContent>> getNotifications() {
        if (notifications.getValue() == null) {
            notifications.setValue(new ArrayList<NotificationContent>());
        }
        return notifications;
    }

    public void removeNotification(NotificationContent notificationContent) {
        List<NotificationContent> n = getNotifications().getValue();
        n.remove(notificationContent);
        notifications.setValue(n);
    }

    public void addNotification(NotificationContent notificationContent) {
        List<NotificationContent> n = getNotifications().getValue();
        n.add(notificationContent);
        notifications.setValue(n);
    }

    public void addNotification(int position, NotificationContent notificationContent) {
        List<NotificationContent> n = getNotifications().getValue();
        n.add(position, notificationContent);
        notifications.setValue(n);
    }
}

最后是RecyclerView.Adapter的代码:

public class NotificationAdapter extends RecyclerView.Adapter<NotificationAdapter.ViewHolder> {

    public class ViewHolder extends RecyclerView.ViewHolder {

        // View Items declaration...

        public ViewHolder(View itemView) {
            super(itemView);
            // View items retrieval ...
        }
    }

    private List<NotificationContent> mNotifications = new ArrayList<>();

    public void updateNotifications(List<NotificationContent> newNotifications) {
        Log.d("NA", "Clearing");
        this.mNotifications.clear();

        Log.d("NA", "Setting");
        this.mNotifications = newNotifications;

        Log.d("NA", "NotifyChangedDataset");
        this.notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // Some code ...
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        // Some code ...     
    }

    @Override
    public int getItemCount() {
        return mNotifications.size();
    }
}

为了了解片段之间的相互作用,下面是nav_graph.xml的图形表示:

但问题是,通过addNotificationFragment添加一个项目后,它最终会清空,下面是代码中给出的日志中的日志:

D/ANDROIDAPP: onViewCreated: addNotification 1
D/ANDROIDAPP: onChanged: detected and done, item size 1
D/NA: Clearing
D/NA: Setting
D/NA: NotifyChangedDataset
D/ANDROIDAPP: onViewCreated: addNotification 2
D/ForceDarkHelper: updateByCheckExcludeList: pkg: com.etilawin.tgvmaxplanner activity: com.etilawin.tgvmaxplanner.MainActivity@df816d4
D/ForceDarkHelper: updateByCheckExcludeList: pkg: com.etilawin.tgvmaxplanner activity: com.etilawin.tgvmaxplanner.MainActivity@df816d4
D/NA: New Adapter
D/NA: Setting adapter
D/NA: Setting layout
D/NA: Item Touche helper
D/NA: Button listener
D/NA: Getting the MLD
D/NA: Adding observer
D/ANDROIDAPP: onChanged: detected and done, item size 0
D/NA: Clearing
D/NA: Setting
D/NA: NotifyChangedDataset
kognpnkq

kognpnkq1#

一旦你返回,你的视图模型就被破坏了,所以你必须重新创建它,所以你必须用构造函数初始化MutableLiveData对象和它的值,这样当模型被清除时,你就可以用这个模型重新赋值了。
所以试试这个方法。

public class NotificationsViewModel extends ViewModel {
    private final MutableLiveData<List<NotificationContent>> notifications;

    public NotificationsViewModel() {
        notifications = new MutableLiveData<>(new ArrayList<>());
    }

    public MutableLiveData<List<NotificationContent>> getNotifications() {
        return notifications;
    }

    public void removeNotification(NotificationContent notificationContent) {
        List<NotificationContent> n = notifications.getValue();
        n.remove(notificationContent);
        notifications.setValue(n);
    }

    public void addNotification(NotificationContent notificationContent) {
        List<NotificationContent> n = notifications.getValue();
        n.add(notificationContent);
        notifications.setValue(n);
    }

    public void addNotification(int position, NotificationContent notificationContent) {
        List<NotificationContent> n = notifications.getValue();
        n.add(position, notificationContent);
        notifications.setValue(n);
    }
}

相关问题