Search code examples
androidsqliteandroid-studioandroid-sharedpreferences

Use database for session management


Can I use a column in table to check if user has logged in.

When user logs in I set value to 1. When he logs out I set to 0.I dont want to use SharedPreferences. Is using it like this inefficient.

I used sharedpreferences first. I set username in the sharedpreference along with other preferences and display username in the nav drawer. When I install the app in another device, I think even the sharedpreference file will be installed and I saw that in the new device the username is displayed in the from the sharedpreference file though that user doesn't exist in the table in that device's database


Solution

  • When user logs in I set value to 1. When he logs out I set to 0

    Here, what will happen is when you set values to 0 or 1 you have to open and close database everytime and will be a hastle to maintain. you have to check it each time what flag is. while in SharedPreferences it will be globally accesible and easy to set flag.

    I would suggest you to use SharedPreferences because

    SharedPreferences is a key/value store where you can save a data under certain key. To read the data from the store you have to know the key of the data. This makes reading the data very easy. But as easy as it is to store a small amount of data as difficult it is to store and read large structured data as you need to define key for every single data, furthermore you cannot really search within the data except you have a certain concept for naming the keys.

    To give an example, SharedPreferences are useful for storing user preferences, where there are just a handful of variables that need storing. SQLite on the other hand would be better for storing data where there is a large set of items, such as song titles in a music library which need to be searched through

    Check SharedPreferences and SQLite.