Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Android's SharedPreferences class from Delphi

I have just started on the Android development path using Delphi XE5, and am trying to build a simple application that needs to be able to persist some entered information (configuration).

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

I have tried searching for "SharedPreferences" in the help, but it returns nothing. A search for "Shared Preferences", on the other hand, gives me too much.

like image 663
HeartWare Avatar asked Dec 03 '22 21:12

HeartWare


1 Answers

In a nutshell, add the required API units to the uses clause - the key ones in your case are AndroidApi.Jni.JavaTypes, AndroidApi.Jni.App, and AndroidApi.Jni.GraphicsContentViewText, together with FMX.Helpers.Android for some glue code - and call it pretty much like you might in Java. Java classes are exposed as interface types with an initial J; in practice the Android API uses nested classes quite a lot, and since Delphi doesn't support nested interface types, these 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(''));

That said, I've recently put out a simple TCustomIniFile descendant that wraps the SharedPreferences API - see here for info:

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

In mapping the API to TCustomIniFile, one small issue I found is the fact SharedPreferences keys are strongly typed, and there doesn't seem to be a way to find out in advance what type a given key has (keys in TCustomIniFile, in contrast, are weakly typed). Because of this, for reading, I use the getAll method to retreive all keys and values as a Map/JMap (Java dictionary object in other words) and read individual keys from there.

like image 179
Chris Rolliston Avatar answered Jan 06 '23 16:01

Chris Rolliston