简体   繁体   中英

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). 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?

**im using MySql as a database and firebase is not used.

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.

You might want to have a look at : 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. I have not actually used something like this before - in the past only using 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. 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 :)

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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