AndroidのSharedPreferencesで値をファイルに保存 ~Delphiソースコード集
Delphiを起動して新規作成を行う
Delphiを起動し、ファイル→新規作成→マルチデバイスアプリケーションをクリックし、空のアプリケーションを選択してOKボタンを押してプロジェクトを作成します。TEdit、TNumberBox、TLabelを以下のように配置します。
ソースコードを記述する
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.EditBox,
FMX.NumberBox, FMX.Controls.Presentation, FMX.Edit, FMX.StdCtrls
,FMX.Platform;
type
TForm1 = class(TForm)
Edit1: TEdit;
NumberBox1: TNumberBox;
StyleBook1: TStyleBook;
Label1: TLabel;
Label2: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
private
{ private 宣言 }
function AppEvent(iAppEvent:TApplicationEvent;iContext:TObject):Boolean;
public
{ public 宣言 }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses
//TAndroidHelper StringToJString JStringToString
Androidapi.Helpers
//TJActivity
,Androidapi.JNI.App
//JSharedPreferences
,Androidapi.JNI.GraphicsContentViewText
//JString
,Androidapi.JNI.JavaTypes;
function TForm1.AppEvent(iAppEvent: TApplicationEvent;
iContext: TObject): Boolean;
var
SaveStr:String;
SaveInt:Integer;
SPre: JSharedPreferences;
SPreE:JSharedPreferences_Editor;
begin
Result:=False;
case iAppEvent of
TApplicationEvent.BecameActive:
begin
//focus取得時
//project.xml ファイルから読む
SPre:=TAndroidHelper.Activity.getSharedPreferences(
StringToJString('project'), TJActivity.JavaClass.MODE_PRIVATE);
SaveStr:=JStringToString(
SPre.getString(
StringToJString('SaveStr'),StringToJString('デフォルト値')
)
);
SaveInt:=SPre.getInt(StringToJString('SaveInt'), 0);
Edit1.Text:=SaveStr;
NumberBox1.Value:=SaveInt;
end;
TApplicationEvent.WillBecomeInactive:
begin
//focus喪失時
//データの保存を行う
SaveStr:=Edit1.Text;
SaveInt:=Trunc(NumberBox1.Value);
//project.xml ファイルに書き込む
SPre:=TAndroidHelper.Activity.getSharedPreferences(
StringToJString('project'), TJActivity.JavaClass.MODE_PRIVATE);
SPreE:=SPre.edit;
SPreE.putString(StringToJString('SaveStr'),StringToJString(SaveStr));
SPreE.putInt(StringToJString('SaveInt'), SaveInt);
SPreE.apply;
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
var APPEventService:IFMXApplicationEventService;
begin
if TPlatformServices.Current.SupportsPlatformService(IFMXApplicationEventService) then
begin
try
APPEventService:=IFMXApplicationEventService(
TPlatformServices.Current.GetPlatformService(IFMXApplicationEventService)
);
except
APPEventService:=nil;
end;
end;
if (APPEventService<>nil) then
APPEventService.SetApplicationEventHandler(AppEvent);
end;
procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
if Key = vkHardwareBack then Key := 0;
end;
end.
