简体   繁体   English

如何在android中保存复选框状态

[英]how to save checkbox state in android

I'm working on an android cooking app (using java) and the homepage has a recycler view populated with recipes which users can like (similar to FaceBook posts).我正在开发一个 android 烹饪应用程序(使用 java),主页有一个回收器视图,其中填充了用户可以喜欢的食谱(类似于 Facebook 帖子)。 The like button is a checkbox, what is the best way to save the state of the like checkbox for every recipe, so when the user signs out of the app and sign in again they will not like the same recipe more than one time.点赞按钮是一个复选框,为每个食谱保存点赞复选框状态的最佳方法是什么,因此当用户退出应用程序并再次登录时,他们不会多次喜欢同一个食谱。

Is using SharedPreference a good idea in this situation?在这种情况下使用 SharedPreference 是个好主意吗?

**im using MySql as a database and firebase is not used. **我使用 MySql 作为数据库并且不使用 firebase。

You could definitely do it using SharedPreferences - but I believe this is more ideally designed for 'preferences' of an application rather than 'application' behaviour state.您绝对可以使用 SharedPreferences 来做到这一点 - 但我相信这更理想地设计用于应用程序的“首选项”而不是“应用程序”行为状态。

You might want to have a look at : https://developer.android.com/topic/libraries/architecture/saving-states?authuser=1您可能想看看: https ://developer.android.com/topic/libraries/architecture/saving-states?authuser=1

Here you will see some options of how to serialize and persist UI states to memory.在这里,您将看到一些有关如何将 UI 状态序列化和持久化到内存的选项。 I have not actually used something like this before - in the past only using SharedPreferences.我以前实际上没有使用过这样的东西——过去只使用 SharedPreferences。

You could of course also create your own storage method, or solution but why bother when ones already exist.您当然也可以创建自己的存储方法或解决方案,但既然已经存在,为什么还要麻烦。

Since you are already using a MySQL database, your application is already grabbing the rows from the DB to show them, so why not add another column called 'checked' which is a boolean type.由于您已经在使用 MySQL 数据库,您的应用程序已经从数据库中获取行来显示它们,所以为什么不添加另一个名为“checked”的列,它是一个布尔类型。 Then when you get your recipes you get the 'checked' variable, and if it is true, then set your UI state of the checkbox to checked, otherwise false :)然后,当您获得食谱时,您将获得“已检查”变量,如果为真,则将复选框的 UI 状态设置为选中,否则为假 :)

The benefit of this approach is that if your app became 'hybrid' and you wanted a website for it too - the data on the database becomes centralised, meaning your persisted user state is the same on mobile as it is web experience, which is a nice benefit!这种方法的好处是,如果您的应用程序变得“混合”并且您也想要一个网站 - 数据库上的数据将变得集中,这意味着您在移动设备上的持久用户状态与 Web 体验相同,这是好福利!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM