Fire a one-off function when the Android application is installed - android

I want to generate a unique ID for my application instance once it is installed. Then I want this to ID to be stored in SharedPreferences so it can be referred to in future.
So the function will look like:
val uniqueID = UUID.randomUUID().toString()
then I would save it to SharedPreferences.
How do I fire this function only once the application is installed (never to be fired again)?
NOTE: My app is being written in Kotlin

Simply check if your shared preference id key returns you any data. If not, it has never been run. Otherwise, it has!
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
if(sharedPreferences.getString("ID", null) == null) {
sharedPreferences.edit().putString("ID", UUID.randomUUID().toString()).apply()
}

Related

How to ensure a global "cache" for the current session of the user even if process is killed

I will try to be as clear and precise as possible in my situation.
Currently developing an Android application with Koltin based on the MVVM pattern, I'm facing a problem that questions my architecture.
My application consists in retrieving the different orders of a user, each order having itself a list of products.
I had imagined setting up a "CommandController" which is actually a singleton.
object CommandController : ICommandController {
override var m_commandRepository: ICommandRepository = CommandRepository()
override var m_commandList: MutableList<Command> = mutableListOf<Command>()
override var m_currentCommand: Command? = null
override var m_currentProduct : Produit? = null
override var m_currentProductIndex : Int = first_index
}
The purpose of this singleton is to act as an intermediary between my viewModels and my repository in order to store the commands received and the currently active command (only 1 active command at a time).
class CommandListViewModel : ViewModel() {
fun fetchCommandList(refreshStrategy: CommandRefreshStrategy){
viewModelScope.launch {
mProgressBar.postValue(true)
mErrorStatus.postValue(null)
try {
mCommandList.postValue(CommandController.getCommandsList(refreshStrategy)) //USE CONTROLLER HERE
mCommandActive.postValue(CommandController.getCurrentCommand()) //USE CONTROLLER HERE
}
catch (e: Exception) {
//this is generic exception handling
//so inform user that something went wrong
mErrorStatus.postValue(ApiResponseError.DEFAULT)
}
finally {
mProgressBar.postValue(false)
}
}
}
}
Note that no element has a reference to the singleton, kotlin initializing it when it is first needed
If I click on the active command in the list, I display its details
I chose to do this to avoid having to remake queries every time I need to get the list of commands, no matter the fragment / activity, even if for the moment I only use it in 1 place.
So my layers are as follows:
A problem I wasn't aware of is annoying.
Indeed, if I change the permissions granted by the application and I come back in the application, the last activity launched is recreated at the last visited fragment.
The problem is that my singleton comes back to its initial state and so my active command is null because the process was killed by the system after the change of permissions.
So I would like to know if there is a way to persist/recover the state of my singleton when I come back into the application.
I've already tried to transfer my singleton to a class inherited from Application, but that doesn't solve the problem of the killed process.
I've read a lot of articles/subjects about shared preferences but I have a lot of problems with it:
The controller is supposed to be a purely business element, except shared preferences need the context
I don't want the current command and the list of commands to remain if the user kills the application himself ( is there a way to differentiate between the death of the process by the system and by the user ??).
Android will kill off OS processes for all kinds of reasons. If you want your data to survive this then you must store it in a persistent store. One of the following:
Store it in a file
Store it in SharedPreferences
Store it in an SQLite database
Store it in the cloud on some server where you can retrieve it later

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.

Firebase Remote Config - check if value exists

I want to implement kind of a proxy for some boolean values in my app. The logic would be as follows:
I receive a set of values from my back-end
I have some of these values set in Firebase as well
When using a value in the app, I first check if it exists in Firebase
3.1. If it exists, take the Firebase value
3.2. If it does not exist, take the backend value
The question is - how can I check if the value exists in Firebase Remote Config?
I found another way, maybe useful for someone else landing here:
val rawValue = remoteConfig.getValue(key)
val exists = rawValue.source == FirebaseRemoteConfig.VALUE_SOURCE_REMOTE
In this case exists will be true only if the value is returned from remote (and and has not been set as default or static provided value). The accepted answer is error prone as does not consider the case where the empty String is a valid String returned from remote
Here the docs for FirebaseRemoteConfigValue
I have found the solution:
Firebase Remote Config fetches ALL values as Strings and only then maps them to other types in convenience methods such as getBoolean(), getLong() etc.
Therefore, a boolean config value existence can be checked as follows:
String value = firebaseRemoteConfig.getString("someKey");
if(value.equals("true")){
//The value exists and the value is true
} else if(value.equals("false")) {
//The value exists and the value is false
} else if(value.equals("")) {
//The value is not set in Firebase
}
Same goes for other types, i.e. a long value set to 64 on firebase will be returned from getString() as "64".
Firebase Remote Config (FRC), actually provides 3 constants to know from where is the value retrieved with getValue(forKey) (documentation)
VALUE_SOURCE_DEFAULT --> value from default set by user
VALUE_SOURCE_REMOTE --> value from remote server
VALUE_SOURCE_STATIC --> value returned is default (FRC don't have the key)
Knowing this, you can do a "wrapper" like this:
class FirebaseRemoteConfigManager {
.....
override fun getBoolean(forKey: String): Boolean? = getRawValue(forKey)?.asBoolean()
override fun getString(forKey: String): String? = getRawValue(forKey)?.asString()
override fun getDouble(forKey: String): Double? = getRawValue(forKey)?.asDouble()
override fun getLong(forKey: String): Long? = getRawValue(forKey)?.asLong()
private fun getRawValue(forKey: String): FirebaseRemoteConfigValue? {
val rawValue = remoteConfig.getValue(forKey)
return if (rawValue.source == FirebaseRemoteConfig.VALUE_SOURCE_STATIC) null else rawValue
}
...
}
If you get a null, you know the key don't exist in FRC.
Take care of using default values as "not exist", because maybe in your FRC you want to set this value, and you will have a false positive
Remote Config already does this, as described in the documentation. You're obliged to provide default values for parameters that haven't been defined in the console. They work exactly as you describe, without having to do any extra work. These defaults will be used until you perform a fetch. If the value is defined in the console, then it will be used instead of the default.

How can I use a view model, with sqlite and a broadcast receiver to update the UI?

I have an application that is used for testing connectivity, it has a 20min alarm, and must contact a server with a unique code, and the server sends an sms with the same code to confirm.
I have all the components working, but I don't know how to get the unique code to automatically update in the UI.
The alarm writes each request into an sqlite DB, and I would like that to automatically update the UI using an observable.
My project is in Kotlin if that makes any difference.
Basically, I'm just not figuring out how to "observe" the sql database for changes or how to have the broadcast receiver and the activity use the same observable
This answer is not complete yet:
In order to do what I wanted, I have so far implemented a shared prefs listener and use that to relay data between the broadcast receivers and the UI. I also implemented an observable object with the new libraries, but I needed to run the app on an older device, so the observable didn't work.
private val listener = SharedPreferences.OnSharedPreferenceChangeListener { prefs, key ->
val value = prefs.getString(key, "")
when(key) {
"sms" -> smsStatus.text = value
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_smschecker)
//setSupportActionBar(toolbar)
getSharedPreferences("SMS_CHECKER", MODE_PRIVATE).registerOnSharedPreferenceChangeListener(listener)
}
then in the broadcast receiver:
val editor = context.getSharedPreferences("SMS_CHECKER", Context.MODE_PRIVATE).edit()
editor.putString("sms", DateFormat.getDateTimeInstance().format(Date()))
editor.apply()
Still working on the sqlite monitoring.

How to save data in an android app

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.

Categories

Resources