Android Tutorial PreferenceActivity tutorial

This tutorial explains how to use the new PreferenceActivity library. This library allows you to create the "standard" settings screen.

The settings screen is hosted in its own activity. As this is an external activity its declaration should be manually added to the manifest file.
I will take this opportunity to give some tips about manual modification of the manifest file which is sometimes required.

Editing AndroidManifest.xml (general overview)
As of Basic4android v1.8 it is no longer required to manually maintain the manifest file. Instead the manifest editor allows you to add extra elements as needed.
See this link for more information: http://www.b4x.com/forum/showthread.php?p=78136
For PreferenceActivity you should add the following code to the manifest editor:
B4X:
AddApplicationText(<activity android:name="anywheresoftware.b4a.objects.preferenceactivity"/>)
Back to PreferenceActivity

preference_1.png


* This image was taken on a Samsung Galaxy Tab device. On other devices the screen will look a bit different based on their default style.

PreferenceActivity library includes two main objects: PreferenceScreen and PreferenceManager.
PreferenceScreen is responsible for building the settings UI. PreferenceManager allows you to read the settings and also modify them by code.
Both these objects should usually be declared in Sub Process_Globals.
The settings are saved in a file in the internal files folder. File handling is done automatically. Note that when you reinstall an application (without uninstalling it) the files are kept so the settings will also be kept.

Each preference entry is stored as a key/value pair. The key is a string (case sensitive) and the value can be either a string or a boolean value.
Each entry must have a unique key.

Building the UI
In order to build the UI we start with a PreferenceScreen object and add entries to this object directly or to PreferenceCategory which can hold other entries.
In the above screenshot you can see a PreferenceScreen with two categories holding other entries.
Note that a PreferenceScreen can also hold secondary PreferenceScreens. In this case when the user presses on the secondary entry a new screen will appear with its entries.
There are three types of preference entries:
- Checkbox
- EditText - Opens an input dialog when the user presses on it.
- List - Open a list dialog when the user presses on it, allowing the user to select a single item.
The code that creates the above UI is:
B4X:
Sub CreatePreferenceScreen
    screen.Initialize("Settings", "")
    'create two categories
    Dim cat1, cat2 As PreferenceCategory
    cat1.Initialize("Category 1")
    cat1.AddCheckBox("check1", "Checkbox1", "This is Checkbox1", True)
    cat1.AddCheckBox("check2", "Checkbox2", "This is Checkbox2", False)
    cat1.AddEditText("edit1", "EditText1", "This is EditText1", "Hello!")
 
    cat2.Initialize("Category 2")
    cat2.AddList("list1", "List1", "This is List1", "Black", _
        Array As String("Black", "Red", "Green", "Blue"))
     
    'add the categories to the main screen
    screen.AddPreferenceCategory(cat1)
    screen.AddPreferenceCategory(cat2)
End Sub
The first string in the Add methods is the entry key followed by the title, summary and default value.
The default value is used if the key does not yet exist.

To show the preferences we use this code:
B4X:
Sub btn_Click
    StartActivity(screen.CreateIntent)
End Sub
Reading the settings
Reading the settings is done with PreferenceManager.
To retrieve the value of a specific key you should use Manager.GetString or Manager.GetBoolean with this key.
You can get a Map with all the stored keys and values by calling Manager.GetAll
If you want to only handle updated settings then you can call Manager.GetUpdatedKeys. This will return a List with the keys that were updated since the last call to this method.
Usually you will want to handle settings updated in Activity_Resume. Activity_Resume will be called right after Activity_Create when you start your program and also when the user closes the preferences screen.
Whether you want to handle all keys or just the updated keys depends on your application.

Tip:
The default values set in the PreferenceScreen.Add calls have no effect till the user actually sees the screen. It is recommended to explicitly set the default values if they do not already exist.
A simple way to do it is with code similar to:
B4X:
Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        CreatePreferenceScreen
        If manager.GetAll.Size = 0 Then SetDefaults
    End If
End Sub

Sub SetDefaults
    'defaults are only set on the first run.
    manager.SetBoolean("check1", True)
    manager.SetBoolean("check2", False)
    manager.SetString("edit1", "Hello!")
    manager.SetString("list1", "Black")
End Sub
This way our code in Activity_Resume will work correctly whether it is the first time the program runs or after the user has closed the settings page.

The program is attached.
 

Attachments

  • PreferenceActivity.zip
    6.5 KB · Views: 943
Last edited:

noclass1980

Active Member
Licensed User
Longtime User
Version

What Android version are you on, and what is your target API level?

its 4.01 I think (no access to Tab at the mo and I'm not sure how to define the API level (what is the API?). Thanks
 

yttrium

Active Member
Licensed User
Longtime User
its 4.01 I think (no access to Tab at the mo and I'm not sure how to define the API level (what is the API?). Thanks

From my WIP tutorial (Part 1, paragraph 6) found here;

From this point, you’ll notice that Android versions are listed by API version, and not specific Android version. This is because Android is based on levels (like .NET 2.0, 3.0, 3.5, 4.0, 4.5), and versions are simply the latest version of Android for each API level. Versions do not implement new features, they only fix bugs - API levels implement new features, at least for development.

Basic4Android supports a level of API8 (Android 2.2, codenamed Froyo) or later, all the way up to API17, more commonly known as Jelly Bean 4.2, codenamed JELLY_BEAN_MR1 (Major Revision 1), as 4.1 was also called Jelly Bean. A fun fact is that Android codenames are based on desserts, in alphabetical order - Cupcake, Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwich, Jelly Bean, and soon, Key Lime Pie.

Anyway, you only need to pick one platform, the one you are developing for. I would suggest you start at API8 or API14, depending on what you need. If you want all users to use the Holo UI that Android currently implements, aim for API14 - otherwise it’s probably best to use API8 for maximum compatibility with older devices. Also, Android 3.x (3.0, 3.1, 3.2) was designed for tablets only - you should only develop for a 2.x or 4.x API level, unless your application is purely for tablets.

You'll notice you have the following line in your Manifest (Project > Manifest Editor).
B4X:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="14"/>

Change it simply to the following in order to change the style.
B4X:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8"/>
 
Last edited:

luke2012

Well-Known Member
Licensed User
Longtime User
There is some way to prohibit the multi-line in edittext?
For example when a user press "return" key the edit box add other lines.

It's possible to handle only one line ?
 
Last edited by a moderator:

mitsusdev

Member
Licensed User
Longtime User
Hi

if i set a parameter as

cat1.AddEditText("Field1", "Title1", "Summary1", "AAA")

and change the value from "AAA" to "BBB"

can i change the Summary data from "Summary1" to "BBB" ?

Thanks
 

mitsusdev

Member
Licensed User
Longtime User
You cannot change the Summary (without creating a new PreferenceScreen).

Ok, thx

i re-create the preference screen to resume event, but in this mode i see the new summary data only where i enter again in preference screen.

can i get the change event of preference value ?
 

mitsusdev

Member
Licensed User
Longtime User
AHPreferenceActivity library allows you to handle events.

i have tried to use AHPReferenceActivity library, but I did not understand how to get event on change parameter value

can you tell me how to do?
 

corwin42

Expert
Licensed User
Longtime User
AHPreferenceActivity library allows you to handle events.

No, that is not correct. I have thought about adding events to the libarary but it is not implemented yet.
 

gabor

New Member
Licensed User
Longtime User
Seekbars, switches,

Hi!

Will all of theese functions be supported?
Settings | Android Developers

Switches, seekbars, time dialogs, number dialogs, icons, checkbox lists, etc.
And also maybe the support of custom dialogs?

Thanks!
 

ciprian

Active Member
Licensed User
Longtime User
Hi there, i'm blocking....
I'm using AHPreferenceActivity to store an IP adress and a PORT.
I have edit1 for the IP and edit2 for the port.
I am seeing the corect values in the log, but i'm not able to write the values into an EditText on my screen.

B4X:
Main.manager.GetString("edit1")
Main.manager.GetString("edit2")
Log(Main.manager.GetAll)

EditText1.Text = "edit1"
EditText2.Text = "edit2"

What's wrong?
 

Eumel

Active Member
Licensed User
Longtime User
It should be

EditText1.Text = Main.manager.GetString("edit1")
EditText2.Text = Main.manager.GetString("edit2")
 

LA3QMA

Member
Licensed User
Longtime User
"The menu button doesn't show"

using "targetSdkVersion="11" because i'm using the GoogleMaps library.

Is there a workaround for this? Or something i can do so that older devices do not install and crash? Or is it possible to include the GoogleMaps library and only execute if android 3+ are in use?
 

boten

Active Member
Licensed User
Longtime User
Where is the preference file kept?
On activity_create I use:
Log(File.ListFiles(File.DirInternal))

but an empty array is returned.
 
Top