B4J Library jSLPreferences Library

This is a thin wrapper for java.util.prefs.Preferences which stores persistent data without you having to worry about where it is stored.

It uses the package name (your applications unique identifier) as it's node, so if you change the package name during development, you'll lose the preferences you've been storing.

It's very simple to use, similar to a Map except that you have to specify the type of data you are storing:


B4X:
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Dim Prefs As SLPreferences


End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    'MainForm.RootPane.LoadLayout("1") 'Load the layout file.

    Prefs.Initialize
 
    'Create a byte array
    Dim a(5) As Byte = Array As Byte(127,100,130,211,120)
    'And store it
    Prefs.PutByteArray("test",a)

    'Store a string
    Prefs.PutString("StrTest","TestStr")

    'Get the string, requires a default in case the key is not found
    Dim Result As String = Prefs.GetString("StrTest","NF")
    If Result = "NF" Then
        Log("StrTest not found")
    Else
        Log(Result)
    End If

    'Get the byte array, again requires a default with which you can test or use as a default
    Dim b(5) As Byte = Prefs.GetByteArray("test",Null)
    If b = Null Then
        Log("test not found")
    Else
        'Log the contents of the byte array
        For Each i As Byte In b
            Log(i)
        Next
    End If

    'Get an array of the keys stored in preferences
    Dim Keys() As String = Prefs.GetKeys

    'And log them
    For Each k As String In Keys
        Log(k)
    Next

    'MainForm.Show
End Sub
Sub MainForm_Closed
    Prefs.Flush
End Sub

I hope you find it useful.

Copy the jar and xml files to your addl libs folder.
 

Attachments

  • Preferences.zip
    3.8 KB · Views: 695
Last edited:

mrred128

Active Member
Licensed User
Longtime User
Where does it put the storage? I ask because sometimes this can be a sensitive issue. How possible would it be to have an override for the location?
 

stevel05

Expert
Licensed User
Longtime User
The actual storage location is controlled by Java. See here My implementation creates a Node on the UserRoot.

If you want the location somewhere in the file system, this is not the library to use. You could use a Map and store it wherever you want to.
 

tsteward

Well-Known Member
Licensed User
Longtime User
I get the following error:
Program started.
Dec 26, 2014 7:32:37 AM java.util.prefs.WindowsPreferences <init>
WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002. Windows RegCreateKeyEx(...) returned error code 5.
 

stevel05

Expert
Licensed User
Longtime User
It's a long time since I created this one, but I don't think it should be needed. Try cleaning the project, if it doesn't help l'll dig out the source.
 
Top