Access Android SharedPreferences class from Delphi

I just started on the development path of Android using Delphi XE5, and am trying to create a simple application that should be able to save some input (configuration).

I found out that the Android SharedPreferences class is probably the easiest way to do this, but I can't figure out how to access this class from Delphi XE5 FMX Mobile.

I tried to find "SharedPreferences" in the help, but returns nothing. On the other hand, searching for β€œgeneral settings” gives me too much.

+4
source share
1 answer

Briefly add the necessary API units to the uses clause - the key ones in your case are AndroidApi.Jni.JavaTypes , AndroidApi.Jni.App and AndroidApi.Jni.GraphicsContentViewText along with FMX.Helpers.Android for some glue code - and call it as you could in Java. Java classes are mapped as interface types with starting J; in practice, the Android API uses nested classes quite a lot, and since Delphi does not support nested interface types, they become ParentClassName_ChildClassName:

 var Prefs: JSharedPreferences; Editor: JSharedPreferences_Editor; I: Integer; F: Single; S: string; begin Prefs := SharedActivity.getPreferences(TJActivity.JavaClass.MODE_PRIVATE); Editor := Prefs.edit; Editor.putInt(StringToJString('MyIntKey'), 999); Editor.putFloat(StringToJString('MyFloatKey'), 123.456); Editor.putString(StringToJString('MyStrKey'), StringToJString('This is a test')); Editor.apply; I := Prefs.getInt(StringToJString('MyIntKey'), 0); F := Prefs.getFloat(StringToJString('MyFloatKey'), 0); S := Prefs.getString(StringToJString('MyIntKey'), StringToJString('')); 

However, I recently released a simple descendant of TCustomIniFile that wraps the SharedPreferences API - see here for information:

http://delphihaven.wordpress.com/2013/09/12/a-few-xe5-related-bits/

When comparing the API with TCustomIniFile one small problem I discovered is that the SharedPreferences keys SharedPreferences strongly typed, and there seems to be no way to know in advance what type the key is (keys in TCustomIniFile , by contrast, are weakly typed). Because of this, I use the getAll method for reading in order to output all the keys and values ​​as Map / JMap (object of the Java dictionary in other words) and read individual keys from there.

+17
source

Source: https://habr.com/ru/post/1502157/


All Articles