AdSense

Monday 16 September 2013

Android - Write application data

(Deutsche Version) Lots of Android apps use a several (small) amount of memory for "data". These datas are e.g. for saving passwords or similar things. I want to explain how to access these datas. At first the reading:

SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
String defaultStringValue = "";
String stringValue = sharedPref.getString("nameOfString", defaultStringValue);


This is analogue to a C# Dictionary with a string as key and (here) a string as value. The value can also be an integer, the syntax is the same. If the key does not exist, defaultStringValue is returned.

Now to the writing of application data:

SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
String stringValue = "asdf";
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("
nameOfString", stringValue);
editor.commit();


Here you can also use int instead of string. Additionally, you can have multiple editor.put... commands directly in a row and only at the end there has to be the editor.commit();. This should cover the basic access on application data. If you want to acces on application data via a widget, you have to use SharedPreferences. The only thing that changes in the code is:

SharedPreferences sharedPref = this.getSharedPreferences("nameOfPreferences", 0);

No comments:

Post a Comment