How to save data in an android app - android

I recently coded an Android app. It's just a simple app that allows you to keep score of a basketball game with a few simple counter intervals. I'm getting demand to add a save feature, so you can save your scores and then load them back up. Currently, when you stop the app, your data is lost. So what I was wondering is what I would have to add to have the app save a label (score) and then load it back up. Thanks guys sorry I don't know much about this stuff.

You have two options, and I'll leave selection up to you.
Shared Preferences
This is a framework unique to Android that allows you to store primitive values (such as int, boolean, and String, although strictly speaking String isn't a primitive) in a key-value framework. This means that you give a value a name, say, "homeScore" and store the value to this key.
SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("homeScore", YOUR_HOME_SCORE);
// Apply the edits!
editor.apply();
// Get from the SharedPreferences
SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
int homeScore = settings.getInt("homeScore", 0);
Internal Storage
This, in my opinion, is what you might be looking for. You can store anything you want to a file, so this gives you more flexibility. However, the process can be trickier because everything will be stored as bytes, and that means you have to be careful to keep your read and write processes working together.
int homeScore;
byte[] homeScoreBytes;
homeScoreBytes[0] = (byte) homeScore;
homeScoreBytes[1] = (byte) (homeScore >> 8); //you can probably skip these two
homeScoreBytes[2] = (byte) (homeScore >> 16); //lines, because I've never seen a
//basketball score above 128, it's
//such a rare occurance.
FileOutputStream outputStream = getApplicationContext().openFileOutput(FILENAME, Context.MODE_PRIVATE);
outputStream.write(homeScoreBytes);
outputStream.close();
Now, you can also look into External Storage, but I don't recommend that in this particular case, because the external storage might not be there later. (Note that if you pick this, it requires a permission)

OP is asking for a "save" function, which is more than just preserving data across executions of the program (which you must do for the app to be worth anything.)
I recommend saving the data in a file on the sdcard which allows you to not only recall it later, but allows the user to mount the device as an external drive on their own computer and grab the data for use in other places.
So you really need a multi-point system:
1) Implement onSaveInstanceState(). In this method, you're passed a Bundle, which is basically like a dictionary. Store as much information in the bundle as would be needed to restart the app exactly where it left off. In your onCreate() method, check for the passed-in bundle to be non-null, and if so, restore the state from the bundle.
2) Implement onPause(). In this method, create a SharedPreferences editor and use it to save whatever state you need to start the app up next time. This mainly consists of the users' preferences (hence the name), but anything else relavent to the app's start-up state should go here as well. I would not store scores here, just the stuff you need to restart the app. Then, in onCreate(), whenever there's no bundle object, use the SharedPreferences interface to recall those settings.
3a) As for things like scores, you could follow Mathias's advice above and store the scores in the directory returned in getFilesDir(), using openFileOutput(), etc. I think this directory is private to the app and lives in main storage, meaning that other apps and the user would not be able to access the data. If that's ok with you, then this is probably the way to go.
3b) If you do want other apps or the user to have direct access to the data, or if the data is going to be very large, then the sdcard is the way to go. Pick a directory name like com/user1446371/basketballapp/ to avoid collisions with other applications (unless you're sure that your app name is reasonably unique) and create that directory on the sdcard. As Mathias pointed out, you should first confirm that the sdcard is mounted.
File sdcard = Environment.getExternalStorageDirectory();
if( sdcard == null || !sdcard.isDirectory()) {
fail("sdcard not available");
}
File datadir = new File(sdcard, "com/user1446371/basketballapp/");
if( !datadir.exists() && !datadir.mkdirs() ) {
fail("unable to create data directory");
}
if( !datadir.isDirectory() ) {
fail("exists, but is not a directory");
}
// Now use regular java I/O to read and write files to data directory
I recommend simple CSV files for your data, so that other applications can read them easily.
Obviously, you'll have to write activities that allow "save" and "open" dialogs. I generally just make calls to the openintents file manager and let it do the work. This requires that your users install the openintents file manager to make use of these features, however.

In onCreate:
SharedPreferences sharedPref = getSharedPreferences("mySettings", MODE_PRIVATE);
String mySetting = sharedPref.getString("mySetting", null);
In onDestroy or equivalent:
SharedPreferences sharedPref = getSharedPreferences("mySettings", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("mySetting", "Hello Android");
editor.commit();

Use SharedPreferences, http://developer.android.com/reference/android/content/SharedPreferences.html
Here's a sample:
http://developer.android.com/guide/topics/data/data-storage.html#pref
If the data structure is more complex or the data is large, use an Sqlite database; but for small amount of data and with a very simple data structure, I'd say, SharedPrefs will do and a DB might be overhead.

There is a lot of options to store your data and Android offers you to chose anyone
Your data storage options are the following:
Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server
Check here for examples and tuto

2021 Answer
Old question but in 2021 you can use several things to save data.
1. Using local database - Room Library
Room is a library that let you store data in the internal SqlLite database that come with your Android device, it's a local database. It's easy and really powerful.
https://developer.android.com/training/data-storage/room
2. Using a remote database - Firebase / Your own database implementation
You can use Firebase services or your own database implementation on your server to remote store your data, that way you could access the data throw multiple devices.
https://firebase.google.com/docs/firestore
3. Storing a local file
You can store all information in a local file saved in the device's external storage, using maybe a .txt file with a \n as data separator. That option looks really "caveman" in 2021.
https://stackoverflow.com/a/14377185/14327871
4. Using SharedPreferences
As many people pointed you can also use the sharedPreferences to store little information as pair of key - value, it's useful for example when saving user preferences across a session.
https://developer.android.com/training/data-storage/shared-preferences?hl=en
For the OP case I would suggest using the 1st or 2nd option.

Shared preferences:
android shared preferences example for high scores?
Does your application has an access to the "external Storage Media". If it does then you can simply write the value (store it with timestamp) in a file and save it. The timestamp will help you in showing progress if thats what you are looking for. {not a smart solution.}

You can store your scores and load them back easily! by using this method
Use this library Paper Db
Add this library on your app:
implementation 'io.github.pilgr:paperdb:2.7.1'
and then initialize it once in the activity onCreate() you are storing:
Paper.init(context)
create a key to store your scores
int myScore=10;
Paper.book().write("scores", myScore);
and get the value of the score :
int mySavedScores=Paper.book().read("scores");
that's It!!! now you can save and access the value even application is closed
and refer the documentation for more methods and information,
it's a Good habit to read the documentation.

Please don't forget one thing - Internal Storage data are deleted when you uninstall the app. In some cases it can be "unexpected feature". Then it's good to use external storage.
Google docs about storage - Please look in particular at getExternalStoragePublicDirectory

Quick answer:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Boolean Music;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//restore preferences
SharedPreferences settings = this.getSharedPreferences(PREFS_NAME, 0);
Music = settings.getBoolean("key", true);
}
#Override
public void onClick() {
//save music setup to system
SharedPreferences settings = this.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("key", Music);
editor.apply();
}
}

In my opinion db4o is the easiest way to go.
Here you can find a tutorial:
http://community.versant.com/documentation/reference/db4o-7.12/java/tutorial/
And here you can download the library:
http://www.db4o.com/community/download.aspx?file=db4o-8.0-java.zip
(Just put the db4o-8.0...-all-java5.jar in the lib directory into your project's libs folder.
If there is no libs folder in you project create it)
As db4o is a object oriented database system you can directly save you objects into the database and later get them back.

use this methods to use sharedPreferences very easily.
private val sharedPreferences = context.getSharedPreferences("myPreferences", Context.MODE_PRIVATE)
fun put(key: String, value: String) = sharedPreferences.edit().putString(key, value).apply()
fun put(key: String, value: Int) = sharedPreferences.edit().putInt(key, value).apply()
fun put(key: String, value: Float) = sharedPreferences.edit().putFloat(key, value).apply()
fun put(key: String, value: Boolean) = sharedPreferences.edit().putBoolean(key, value).apply()
fun put(key: String, value: Long) = sharedPreferences.edit().putLong(key, value).apply()
fun getString(key: String, defaultValue: String? = null): String? = sharedPreferences.getString(key, defaultValue)
fun getInt(key: String, defaultValue: Int = -1): Int = sharedPreferences.getInt(key, defaultValue)
fun getFloat(key: String, defaultValue: Float = -1F): Float = sharedPreferences.getFloat(key, defaultValue)
fun getBoolean(key: String, defaultValue: Boolean = false): Boolean = sharedPreferences.getBoolean(key, defaultValue)
fun getLong(key: String, defaultValue: Long = -1L): Long = sharedPreferences.getLong(key, defaultValue)
fun clearAll() = sharedPreferences.edit().clear().apply()
put them in a class and get context in its constructor.

Related

How and where do i declare a global Variable for saving Data

I am trying to build my very first Kotlin App where I save my private
Hourly Contingent.
For example, if I study 2 hours, I add 2 hours to it. If I play video games for 30 Minutes I subtract 2 hours, so that I'm allowed to play video games for 15 minutes for every hour of studying.
I am saving my Data with sharedPreferences and I get this Data from my TextView. When I start the Application, I just load the Data to my TextView. So while running the App, the TextView saves the hours and minutes I already gained:
//Saves the TextView from the Main Activity (Probably bad practice but its my first Kotlin APP and i will improve later)
private fun saveData(){
val hcString = findViewById(R.id.hourly_contingent) as TextView
val hcStrArr = hcString.text.split(":").toTypedArray()
val hcIntArr = arrayOf(hcStrArr[0].toInt(), hcStrArr[1].toInt())
val sharedPreferences = getSharedPreferences("hourly_contingent", Context.MODE_PRIVATE);
val editor = sharedPreferences.edit();
editor.apply(){
putInt("hc_hours", hcIntArr[0])
putInt("hc_minutes", hcIntArr[1])
}.apply()
Toast.makeText(this, "Data saved", Toast.LENGTH_SHORT).show()
}
//Puts the saved Data to the hourly_contingent String
private fun loadData(){
val sharedPreferences = getSharedPreferences("hourly_contingent", Context.MODE_PRIVATE);
val hcHours = sharedPreferences.getInt("hc_hours", 0)
val hcMinutes = sharedPreferences.getInt("hc_minutes", 0)
val hourly_contingent = findViewById(R.id.hourly_contingent) as TextView
val hcString = hcHours.toString() + ":" + hcMinutes.toString()
hourly_contingent.text = hcString
}
I know this is very bad practice but I don't know how to it better.
Should I use a global variable?
Where and how do I declare that?
Should I create a new File MyApplication.kt and in there a global class like that:
public class Global : Application() {
open var homeAPIResponse: String = "defaultValue"
}
A little help would be really nice!
First thing i would advise you is to read about basic design patterns for android. Model-View-Controller and Model-View-ViewModel. They really can help you sort out data scope problems and show good practices on presenting data on android. (https://developer.android.com/jetpack/guide)
There are a lot of amazing basics android courses on udacity, made by android devs - all of them, free. They will definitely clarify most of the problems you described here. How you should store data or how should you prepare it for user to display.
So to somehow answer your question:
Right now your piece of code is called from MainActivity. Everything your varaibles store within Activity class will be gone after the Activity is destroyed. It stems from the lifecycle of an activity (another good topic to read about). To persist some data, even after app is closed (i.e. activity is destroyed), you either can use SharedPreferences (perfect for small data, even better for data related to UI configuration), file storage or database. Last one is pretty easy by means of Room library, but maybe overkill for storing one float value. I hope this answers your question.
Reading link - on data persistency:
(https://developer.android.com/training/data-storage)

AutoBackUp with EncryptedSharedPreferences failing to restore

I am using EncryptedSharedPreferences to store user information locally (see this if you are not familiar). I have implemented AutoBackUp with BackUp rules. I backed up the preferences, cleared data on my app, and attempted to restore the data (following the steps outlined for backup and restore).
Looking at Device File Explorer in Android Studio, I can confirm that my Preferences file is being restored (it is properly named and there is encrypted data in it). However, my app functions as if the preferences file does not exist.
What am I missing?
Preferences code:
class PreferenceManager(context: Context) {
companion object {
private const val KEY_STORE_ALIAS = "APP_KEY_STORE"
private const val privatePreferences = "APP_PREFERENCES"
}
// See https://developer.android.com/topic/security/data#kotlin for more info
private val sharedPreferences = EncryptedSharedPreferences.create(
privatePreferences,
KEY_STORE_ALIAS,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
init {
//val all = sharedPreferences.all
//for (item in all) {
//Log.e("PREFERENCES", "${item.key} - ${item.value}")
//}
}
#SuppressLint("ApplySharedPref")
fun clear() {
// Normally you want apply, but we need the changes to be done immediately
sharedPreferences.edit().clear().commit()
}
fun readBoolean(key: String, defaultValue: Boolean): Boolean {
return sharedPreferences.getBoolean(key, defaultValue)
}
fun readDouble(key: String): Double {
return sharedPreferences.getFloat(key, 0f).toDouble()
}
fun readString(key: String): String {
return sharedPreferences.getString(key, "")!!
}
fun removePreference(key: String) {
sharedPreferences.edit().remove(key).apply()
}
fun writeBoolean(key: String, value: Boolean) {
sharedPreferences.edit().putBoolean(key, value).apply()
}
fun writeDouble(key: String, value: Double) {
sharedPreferences.edit().putFloat(key, value.toFloat()).apply()
}
fun writeString(key: String, value: String) {
sharedPreferences.edit().putString(key, value).apply()
}
}
I am not implementing a BackupAgent currently.
From my understanding Jetpack Security relies on keys that are generated on the device hardware, and so it is that you cannot rely on that the original key is still there after a backup restore (think about changed devices).
Encryption is only as secure as the security of the key, and as long as it cannot leave the Keystore or the device, backup and restore cannot work automatically (without user interaction).
My approach (1) would be that you ask the user for a password, encrypt your regular shared preferences based on that password (maybe with another encryption library: for example https://github.com/iamMehedi/Secured-Preference-Store), and save the password with encryptedsharedpreferences from Jetpack. After restore of the backup ask the user for the password, save it again with Jetpack and decrypt the regular SharedPreferences.
That way even when the hardware keystore changes, you can restore the backup. The disadvantage is, that the user needs to remember a password.
I follow this approach with my app, just not with sharedpreferences (they are not sensible in my use case), but with the app database.
Another approach (2) would be to check for encrypted backups (available from Pie on), if you are only concerned about backups in the cloud. With that approach you don't encrypt the sharedpreferences locally, but the backups are encrypted by default. If you need local encryption, this approach is not for you, but the advantage is, that the user must only type in his/her lockscreen password on restore of the backups and after that everything gets restored without further user interaction.
A combination is also thinkable and is preferrable, if you can live without local encryption: Approach 1 for pre-9 and Approach 2 for post-9.
As #Floj12 mentioned EncryptedSharedPreferences use Keystore and you cannot back up the Keystore, so when your encrypted data will be restored you won't be able to decrypt it.
This is very sad that Google force two things that don't work together. Keystore on Android doesn't have a backup option like Keychain on iOS.
Here I will give you more option how can you backup the data:
Store user data one backend
Use a user-stored token to decrypt the backup
Have a static password for all apps
Export backup manually by the user in settings
I wrote about it more here:
https://medium.com/#thecodeside/android-auto-backup-keystore-encryption-broken-heart-love-story-8277c8b10505

Storing received notifications in my android app? [duplicate]

I recently coded an Android app. It's just a simple app that allows you to keep score of a basketball game with a few simple counter intervals. I'm getting demand to add a save feature, so you can save your scores and then load them back up. Currently, when you stop the app, your data is lost. So what I was wondering is what I would have to add to have the app save a label (score) and then load it back up. Thanks guys sorry I don't know much about this stuff.
You have two options, and I'll leave selection up to you.
Shared Preferences
This is a framework unique to Android that allows you to store primitive values (such as int, boolean, and String, although strictly speaking String isn't a primitive) in a key-value framework. This means that you give a value a name, say, "homeScore" and store the value to this key.
SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("homeScore", YOUR_HOME_SCORE);
// Apply the edits!
editor.apply();
// Get from the SharedPreferences
SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
int homeScore = settings.getInt("homeScore", 0);
Internal Storage
This, in my opinion, is what you might be looking for. You can store anything you want to a file, so this gives you more flexibility. However, the process can be trickier because everything will be stored as bytes, and that means you have to be careful to keep your read and write processes working together.
int homeScore;
byte[] homeScoreBytes;
homeScoreBytes[0] = (byte) homeScore;
homeScoreBytes[1] = (byte) (homeScore >> 8); //you can probably skip these two
homeScoreBytes[2] = (byte) (homeScore >> 16); //lines, because I've never seen a
//basketball score above 128, it's
//such a rare occurance.
FileOutputStream outputStream = getApplicationContext().openFileOutput(FILENAME, Context.MODE_PRIVATE);
outputStream.write(homeScoreBytes);
outputStream.close();
Now, you can also look into External Storage, but I don't recommend that in this particular case, because the external storage might not be there later. (Note that if you pick this, it requires a permission)
OP is asking for a "save" function, which is more than just preserving data across executions of the program (which you must do for the app to be worth anything.)
I recommend saving the data in a file on the sdcard which allows you to not only recall it later, but allows the user to mount the device as an external drive on their own computer and grab the data for use in other places.
So you really need a multi-point system:
1) Implement onSaveInstanceState(). In this method, you're passed a Bundle, which is basically like a dictionary. Store as much information in the bundle as would be needed to restart the app exactly where it left off. In your onCreate() method, check for the passed-in bundle to be non-null, and if so, restore the state from the bundle.
2) Implement onPause(). In this method, create a SharedPreferences editor and use it to save whatever state you need to start the app up next time. This mainly consists of the users' preferences (hence the name), but anything else relavent to the app's start-up state should go here as well. I would not store scores here, just the stuff you need to restart the app. Then, in onCreate(), whenever there's no bundle object, use the SharedPreferences interface to recall those settings.
3a) As for things like scores, you could follow Mathias's advice above and store the scores in the directory returned in getFilesDir(), using openFileOutput(), etc. I think this directory is private to the app and lives in main storage, meaning that other apps and the user would not be able to access the data. If that's ok with you, then this is probably the way to go.
3b) If you do want other apps or the user to have direct access to the data, or if the data is going to be very large, then the sdcard is the way to go. Pick a directory name like com/user1446371/basketballapp/ to avoid collisions with other applications (unless you're sure that your app name is reasonably unique) and create that directory on the sdcard. As Mathias pointed out, you should first confirm that the sdcard is mounted.
File sdcard = Environment.getExternalStorageDirectory();
if( sdcard == null || !sdcard.isDirectory()) {
fail("sdcard not available");
}
File datadir = new File(sdcard, "com/user1446371/basketballapp/");
if( !datadir.exists() && !datadir.mkdirs() ) {
fail("unable to create data directory");
}
if( !datadir.isDirectory() ) {
fail("exists, but is not a directory");
}
// Now use regular java I/O to read and write files to data directory
I recommend simple CSV files for your data, so that other applications can read them easily.
Obviously, you'll have to write activities that allow "save" and "open" dialogs. I generally just make calls to the openintents file manager and let it do the work. This requires that your users install the openintents file manager to make use of these features, however.
In onCreate:
SharedPreferences sharedPref = getSharedPreferences("mySettings", MODE_PRIVATE);
String mySetting = sharedPref.getString("mySetting", null);
In onDestroy or equivalent:
SharedPreferences sharedPref = getSharedPreferences("mySettings", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("mySetting", "Hello Android");
editor.commit();
Use SharedPreferences, http://developer.android.com/reference/android/content/SharedPreferences.html
Here's a sample:
http://developer.android.com/guide/topics/data/data-storage.html#pref
If the data structure is more complex or the data is large, use an Sqlite database; but for small amount of data and with a very simple data structure, I'd say, SharedPrefs will do and a DB might be overhead.
There is a lot of options to store your data and Android offers you to chose anyone
Your data storage options are the following:
Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server
Check here for examples and tuto
2021 Answer
Old question but in 2021 you can use several things to save data.
1. Using local database - Room Library
Room is a library that let you store data in the internal SqlLite database that come with your Android device, it's a local database. It's easy and really powerful.
https://developer.android.com/training/data-storage/room
2. Using a remote database - Firebase / Your own database implementation
You can use Firebase services or your own database implementation on your server to remote store your data, that way you could access the data throw multiple devices.
https://firebase.google.com/docs/firestore
3. Storing a local file
You can store all information in a local file saved in the device's external storage, using maybe a .txt file with a \n as data separator. That option looks really "caveman" in 2021.
https://stackoverflow.com/a/14377185/14327871
4. Using SharedPreferences
As many people pointed you can also use the sharedPreferences to store little information as pair of key - value, it's useful for example when saving user preferences across a session.
https://developer.android.com/training/data-storage/shared-preferences?hl=en
For the OP case I would suggest using the 1st or 2nd option.
Shared preferences:
android shared preferences example for high scores?
Does your application has an access to the "external Storage Media". If it does then you can simply write the value (store it with timestamp) in a file and save it. The timestamp will help you in showing progress if thats what you are looking for. {not a smart solution.}
You can store your scores and load them back easily! by using this method
Use this library Paper Db
Add this library on your app:
implementation 'io.github.pilgr:paperdb:2.7.1'
and then initialize it once in the activity onCreate() you are storing:
Paper.init(context)
create a key to store your scores
int myScore=10;
Paper.book().write("scores", myScore);
and get the value of the score :
int mySavedScores=Paper.book().read("scores");
that's It!!! now you can save and access the value even application is closed
and refer the documentation for more methods and information,
it's a Good habit to read the documentation.
Please don't forget one thing - Internal Storage data are deleted when you uninstall the app. In some cases it can be "unexpected feature". Then it's good to use external storage.
Google docs about storage - Please look in particular at getExternalStoragePublicDirectory
Quick answer:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Boolean Music;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//restore preferences
SharedPreferences settings = this.getSharedPreferences(PREFS_NAME, 0);
Music = settings.getBoolean("key", true);
}
#Override
public void onClick() {
//save music setup to system
SharedPreferences settings = this.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("key", Music);
editor.apply();
}
}
In my opinion db4o is the easiest way to go.
Here you can find a tutorial:
http://community.versant.com/documentation/reference/db4o-7.12/java/tutorial/
And here you can download the library:
http://www.db4o.com/community/download.aspx?file=db4o-8.0-java.zip
(Just put the db4o-8.0...-all-java5.jar in the lib directory into your project's libs folder.
If there is no libs folder in you project create it)
As db4o is a object oriented database system you can directly save you objects into the database and later get them back.
use this methods to use sharedPreferences very easily.
private val sharedPreferences = context.getSharedPreferences("myPreferences", Context.MODE_PRIVATE)
fun put(key: String, value: String) = sharedPreferences.edit().putString(key, value).apply()
fun put(key: String, value: Int) = sharedPreferences.edit().putInt(key, value).apply()
fun put(key: String, value: Float) = sharedPreferences.edit().putFloat(key, value).apply()
fun put(key: String, value: Boolean) = sharedPreferences.edit().putBoolean(key, value).apply()
fun put(key: String, value: Long) = sharedPreferences.edit().putLong(key, value).apply()
fun getString(key: String, defaultValue: String? = null): String? = sharedPreferences.getString(key, defaultValue)
fun getInt(key: String, defaultValue: Int = -1): Int = sharedPreferences.getInt(key, defaultValue)
fun getFloat(key: String, defaultValue: Float = -1F): Float = sharedPreferences.getFloat(key, defaultValue)
fun getBoolean(key: String, defaultValue: Boolean = false): Boolean = sharedPreferences.getBoolean(key, defaultValue)
fun getLong(key: String, defaultValue: Long = -1L): Long = sharedPreferences.getLong(key, defaultValue)
fun clearAll() = sharedPreferences.edit().clear().apply()
put them in a class and get context in its constructor.

Shared Preferences is read as the wrong type

I'm reading SharedPreferences in my app at startup, and after a few runs it will crash and tell me that I'm trying to cast from a String to a Boolean. Below is the code that I use to read and write this value.
// Checks if the realm has been copied to the device, and copies it if it hasn't.
private void copyRealm() {
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
if (!sharedPreferences.getBoolean(getString(R.string.pref_copied), false)) {
// Copy the realm to device.
final String path = copyBundledRealmFile(getResources().openRawResource(R.raw.realm), getString(R.string.realm_name));
// Save the path of the realm, and that the realm has been copied.
sharedPreferences.edit()
.putBoolean(getString(R.string.pref_copied), true)
.putString(getString(R.string.pref_path), path)
.apply();
}
}
The two strange things are that it doesn't start happening for a few builds, and so far it has only happened on a simulator. I haven't been able to check a physical device yet, but I've also been running this code without change for several months and had no trouble.
Why would I be getting this message?
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean
at android.app.SharedPreferencesImpl.getBoolean(SharedPreferencesImpl.java:293)?
Take a look at this question Android getDefaultSharedPreferences.
It seems it's a better idea to just use
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
or
SharedPreferences references1=getSharedPreferences("some_name",MODE_PRIVATE);
instead of using
SharedPreferences preferences= getDefaultSharedPreferences(this);
From the documentation:
getPreferences(MODE_PRIVATE) retrieves a SharedPreferences object for
accessing preferences that are private to this activity. This simply
calls the underlying getSharedPreferences(String, int) method by
passing in this activity's class name as the preferences name.
I regularly use one of these two approaches and had no problem of any kind so far.

What are things to keep in mind while using Shared Preferences android?

I am working on a simple android application.
The application has the functionality of user login which is connected to php.
I am successful in getting login functionality done well. What I want now is to save the username so that I can use it anywhere and anytime in my application. After going through some SO threads I came to know that this is doable using android sharedPreferences.
But prior to implementing them I want to know some stuff that I should keep in mind while using sharedPreferences like
what is basic task of shared preferences?
what things to keep in mind while actually using them?
what is proper way to programatically implement them in code?
and finally how to remove them after they are used?
what is basic task of shared preferences?
SharedPreferences are essentially used when you need your application to store persistent data. I consider using it when a Database is (for the sheer purposes of size / data to be stored) isn't really required.
what things to keep in mind while actually using them?
You can save just about anything that you typically require for your application to perform it's task. For example, in a gaming application, you could store the user's scores. However, since the SharedPreferences file/s can be accessed by anyone on a rooted device, you wouldn't want to store passwords. If you absolutely must store them anyway, you should implement your own algorithm to encrypt it. In an app of mine, I store URL's to a user's profile picture on Facebook and Twitter. That is already in the public domain.
what is proper way to programatically implement them in code?
If you are going to use SharedPreference in say, just one or two Activities, you use something like this to add values to the SharedPreference file:
// THE SHAREDPREFERENCE INSTANCE
SharedPreferences sharedPrefs;
// THE EDITOR INSTANCE
Editor editor;
// A CONSTANT STRING TO PROVIDE A NAME TO THE SHAREDPREFERENCE FILE
private static final String PRIVATE_PREF = "some_file_name";
// INSTANTIATE THE SHAREDPREFERENCE INSTANCE
sharedPrefs = getApplicationContext().getSharedPreferences(PRIVATE_PREF, Context.MODE_PRIVATE);
// INSTANTIATE THE EDITOR INSTANCE
editor = sharedPrefs.edit();
// ADD VALUES TO THE PREFERENCES FILE
editor.putLong(UNIQUE_KEY_NAME, VALUE);
editor.putString(UNIQUE_KEY_NAME, VALUE);
editor.putString(UNIQUE_KEY_NAME, VALUE);
editor.putString(UNIQUE_KEY_NAME, VALUE);
// THIS STEP IS VERY IMPORTANT. THIS ENSURES THAT THE VALUES ADDED TO THE FILE WILL ACTUALLY PERSIST
// COMMIT THE ABOVE DATA TO THE PREFERENCE FILE
editor.commit();
To fetch the values out of the file:
String someString = sharedPrefs.getString(UNIQUE_KEY_NAME, null);
long someLong = sharedPrefs.getLong(UNIQUE_KEY_NAME, 0);
If you need to reuse the contents / values from the SharedPreference file, this here is a nice tutorial on creating a helper class that will let any number of Activites to access the values instead of coding the above in every single one of them: http://megasnippets.com/source-codes/java/sharedpreferences_helper_class_android
and finally how to remove them after they are used?
// INSTANTIATE THE EDITOR INSTANCE
editor = sharedPrefs.edit();
// TO CLEAR A SELECT FEW OF THE VALUES:
editor.remove(KEY_FOR_THE_VALUE_TO_BE_REMOVED);
// ALTERNATIVELY, TO CLEAR ALL VALUES IN THE FILE:
editor.clear();
Note: Any SharedPreferences file/s you may create will be removed when the user manually clears the app data from the device's Settings.
Links For Further Reading:
http://www.vogella.com/articles/AndroidFileBasedPersistence/article.html
http://saigeethamn.blogspot.in/2009/10/shared-preferences-android-developer.html
http://www.mybringback.com/tutorial-series/12260/android-sharedpreferences-example/
http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
How to Save/Read 'username' from SharedPreferences Persistent Storage
Basic Task:
Persistent storage.
Keep In Mind:
Is there so much data that you might be better off using a database or flat file storage?
Proper Way to Save and Read "username":
String key = "username";
String value = "John Doe";
// Save
SharedPreferences.Editor editor = context.getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE).edit();
editor.putString(key, value);
editor.commit();
// Read
String def = "";
SharedPreferences settings = context.getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE);
if(!settings.contains(key)) {
// Warn user that there is nothing to read and/or return a default value: "def"
}
String value = settings.getString(key, def);
About the basic task : you can read on Storage Options at developer.android.com.
About the keep in mind : try to avoid saving sensetive data to your application in shared preferences,because user can easily access the data.
You can find your shared preferences xml file in /data/data/your_application.package.name/shared_prefs/shared_prefs_name.xml
Implementation :
Usualy I am creating class with static methods like this :
public class MySharedPreferences {
private static final String APP_SHARED_PREFS = "my_prefs";
private static final String KEY_LOGIN = "username";
public static void setUsername(Context context, String username) {
SharedPreferences sharedPreferences = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putString(KEY_USERNAME, login);
editor.commit();
}
public static String getUsername(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
return sharedPreferences.getString(KEY_USERNAME, null);
}
}

Categories

Resources