📜 ⬆️ ⬇️

Android App Configuration: Rapid Development

image When developing mobile applications, it is often necessary to store the settings of the application (the color theme chosen by the user, the password to access the application, the synchronization settings with the server, etc.). Since such tasks occur quite often, Google took care of the developers and created a mechanism for quick and easy implementation of this functionality. This mechanism allows you to easily create, save, display and produce various manipulations with the settings of the application. Moreover, it allows you to automatically create a user interface. When describing the type of the settings parameter, a part of the user interface is automatically generated depending on the type of the parameter (boolean - checkbox, String - input field, ...) without writing code. Sounds good for fast development, right?

The first step in implementing the application settings mechanism is inheriting the activity of your application's screen from the PreferenceActivity class. This class is inherited from the ListActivity class .
and allows you to create a user interface as described in the XML resource file. Moreover, this class allows you to automatically save settings in SharedPreferences imperceptibly for you. SharedPreferences - an interface that allows you to access and manipulate application configuration data manually by calling the getSharedPreferences method from your Activity (read more Android Essentials: Application Preferences ). In order to link together our class inherited from PreferenceActivity and an XML file describing configuration parameters, use the addPreferencesFromResource method:

  1. ...
  2. @Override
  3. public void onCreate ( Bundle savedInstanceState ) {
  4. super . onCreate ( savedInstanceState ) ;
  5. addPreferencesFromResource ( R. xml . preferences ) ;
  6. }
  7. ...

Now you need to create a res / xml / preferences.xml file which is a description of our list of application configuration options and will be picked up by our PreferenceActivity . This XML file has a specific format allowing the description of configuration parameter types. All types derive from the Preference class, which is the base unit of the user interface and generates a View that will subsequently appear in the right place of the user interface and will be associated with a SharedPreferences object that can be retrieved and saved. Consider the frequently used subclasses used to describe the types of configuration parameters:

It should also be noted that individual parameters can be grouped into categories using the PreferenceCategory class, which groups Preference objects and displays an inactive group header.

Now we describe what we want to see in our XML description. We will have two categories. In the first place a CheckBoxPreference which will activate / deactivate the data synchronization of our hypothetical application and the ListPreference in which we will set the data synchronization frequency. As you have probably noticed, there is a dependency between these two parameters; if the first is not selected, then the second must be deactivated. This is achieved by using the android: dependency attribute. In the second category we will place the EditTextPreference with which we will set the greeting text. Imagine all this in the form of XML:
  1. <? xml version = "1.0" encoding = "utf-8" ?>
  2. <PreferenceScreen xmlns: android = " schemas.android.com/apk/res/android" >
  3. <PreferenceCategory
  4. android: title = "First Category"
  5. android: key = "first_category" >
  6. <CheckBoxPreference
  7. android: key = "perform_updates"
  8. android: summary = "Enable or disable data updates"
  9. android: title = "Enable updates"
  10. android: defaultValue = "true"
  11. />
  12. <ListPreference
  13. android: key = "updates_interval"
  14. android: title = "Updates interval"
  15. android: summary = "Define how often updates will be performed"
  16. android: defaultValue = "1000"
  17. android: entries = "@ array / updateInterval"
  18. android: entryValues = "@ array / updateIntervalValues"
  19. android: dependency = "perform_updates"
  20. />
  21. </ PreferenceCategory >
  22. <PreferenceCategory
  23. android: title = "Second Category"
  24. android: key = "second_category" >
  25. <EditTextPreference
  26. android: key = "welcome_message"
  27. android: title = "Welcome Message"
  28. android: summary = "Define
  29. android: dialogTitle = "Welcome Message"
  30. android: dialogMessage = "Provide a message"
  31. android: defaultValue = "Default welcome message" />
  32. </ PreferenceCategory >
  33. </ PreferenceScreen >

Notice that for the ListPreference we specified an attribute android: entries which indicates where the possible values ​​of the list are stored. These values ​​are stored in the res / values ​​/ arrays.xml XML file. The values ​​of “updateInterval” and “updateIntervalValue” are stored in this file. In fact, these are just key-value pairs, the keys are stored in the first array, and the values ​​are in the second:
  1. <? xml version = "1.0" encoding = "utf-8" ?>
  2. <resources >
  3. <string-array name = "updateInterval" >
  4. <item name = "1000" > Every 1 second </ item >
  5. <item name = "5000" > Every 5 seconds </ item >
  6. <item name = "30000" > Every 30 seconds </ item >
  7. <item name = "60000" > Every 1 minute </ item >
  8. <item name = "300000" > Every 5 minutes </ item >
  9. </ string-array >
  10. <string-array name = "updateIntervalValues" >
  11. <item name = "1000" > 1000 </ item >
  12. <item name = "5000" > 5000 </ item >
  13. <item name = "30000" > 30000 </ item >
  14. <item name = "60000" > 60000 </ item >
  15. <item name = "300000" > 300000 </ item >
  16. </ string-array >
  17. </ resources >

I will add one more useful point that can be useful. It is often necessary to restrict access to the application using a password or PIN code that is set in the application configuration. It is obvious that for these purposes EditTextPreference is used. But it would be nice in the case of a password or PIN-code to hide the entered characters, and for the code also to restrict input to numbers only. To do this, you can use the attributes android: password and android: inputType respectively:
  1. <EditTextPreference
  2. android: key = "pin"
  3. android: title = "PIN code"
  4. android: summary = "If login screen is enabled"
  5. android: dialogTitle = "PIN code"
  6. android: dialogMessage = "Provide a PIN"
  7. android: defaultValue = ""
  8. android: inputType = "number"
  9. android: password = "true"
  10. android: dependency = "runLoginScreen"
  11. />

As mentioned above, the main part of the work is undertaken by the andriod framework itself. In order to show how to read already set parameters, we will create another screen activity, which will be launched from our main activity. But first look at the main code:
  1. package com.javacodegeeks.android.preferences ;
  2. import android.content.Intent ;
  3. import android.os.Bundle ;
  4. import android.preference.PreferenceActivity ;
  5. import android.view.Menu ;
  6. import android.view.MenuItem ;
  7. public class QuickPrefsActivity extends PreferenceActivity {
  8. @Override
  9. public void onCreate ( Bundle savedInstanceState ) {
  10. super . onCreate ( savedInstanceState ) ;
  11. addPreferencesFromResource ( R. xml . preferences ) ;
  12. }
  13. @Override
  14. public boolean onCreateOptionsMenu ( Menu menu ) {
  15. menu. add ( Menu . NONE , 0 , 0 , "Show current settings" ) ;
  16. return super . onCreateOptionsMenu ( menu ) ;
  17. }
  18. @Override
  19. public boolean onOptionsItemSelected ( MenuItem item ) {
  20. switch ( item. getItemId ( ) ) {
  21. case 0 :
  22. startActivity ( new Intent ( this , ShowSettingsActivity. class ) ) ;
  23. return true ;
  24. }
  25. return false ;
  26. }
  27. }

We created an optional menu with a single MenuItem item using the onCreateOptionsMenu method. When a user clicks on a menu item, we process this event in the onOptionsItemSelected method and start a new activity using the startActivity method. (more details using the options menus and customized dialogs for user interaction , Launching new activities with intents ).
')
Now we will create the second ShowSettingsActivity activity to display the application configuration parameters. But first we need to describe the new activity in the manifest AndroidManifest.xml file:
  1. <? xml version = "1.0" encoding = "utf-8" ?>
  2. <manifest xmlns: android = " schemas.android.com/apk/res/android"
  3. package = "com.javacodegeeks.android.preferences"
  4. android: versionCode = "1"
  5. android: versionName = "1.0" >
  6. <application android: icon = "@ drawable / icon" android: label = "@ string / app_name" >
  7. <activity android: name = ".QuickPrefsActivity" android: label = "@ string / app_name" >
  8. <intent-filter >
  9. <action android: name = "android.intent.action.MAIN" />
  10. <category android: name = "android.intent.category.LAUNCHER" />
  11. </ intent-filter >
  12. </ activity >
  13. <activity android: name = ".ShowSettingsActivity" />
  14. </ application >
  15. <uses-sdk android: minSdkVersion = "3" />
  16. </ manifest >

The second activity code looks like this:
  1. package com.javacodegeeks.android.preferences ;
  2. import android.app.Activity ;
  3. import android.content.SharedPreferences ;
  4. import android.os.Bundle ;
  5. import android.preference.PreferenceManager ;
  6. import android.widget.TextView ;
  7. public class ShowSettingsActivity extends Activity {
  8. @Override
  9. protected void onCreate ( Bundle savedInstanceState ) {
  10. super . onCreate ( savedInstanceState ) ;
  11. setContentView ( R. layout . show_settings_layout ) ;
  12. SharedPreferences sharedPrefs = PreferenceManager. getDefaultSharedPreferences ( this ) ;
  13. StringBuilder builder = new StringBuilder ( ) ;
  14. builder. append ( "n" + sharedPrefs. getBoolean ( "perform_updates" , false ) ) ;
  15. builder. append ( "n" + sharedPrefs. getString ( "updates_interval" , "-1" ) ) ;
  16. builder. append ( "n" + sharedPrefs. getString ( "welcome_message" , "NULL" ) ) ;
  17. TextView settingsTextView = ( TextView ) findViewById ( R. id . Settings_text_view ) ;
  18. settingsTextView. setText ( builder. toString ( ) ) ;
  19. }
  20. }

Here we retrieve application configuration parameters as a SharedPreferences class using the static getDefaultSharedPreferences method of the PreferenceManager class. Further, depending on the data type of the parameter, we use the appropriate data retrieval method (for example, getBoolean or getString ). The second argument in the data extraction method is the default value, in case a parameter with that name has not yet been specified. As parameter names, we use the keys specified in the XML file preferences.xml . Parameter values ​​are concatenated and displayed in a TextView .

Here is a simple user interface description for the second activity:
  1. <? xml version = "1.0" encoding = "utf-8" ?>
  2. <LinearLayout
  3. xmlns: android = " schemas.android.com/apk/res/android"
  4. android: orientation = "vertical"
  5. android: layout_width = "fill_parent"
  6. android: layout_height = "fill_parent"
  7. >
  8. <Textview
  9. android: id = "@ + id / settings_text_view"
  10. android: layout_width = "fill_parent"
  11. android: layout_height = "wrap_content"
  12. />
  13. </ LinearLayout >

Let's run the application, we will see a list of our parameters:

image

Click on “Updates Interval” and see a list of possible values:

List of possible parameter values

Click on the “Welcome Message” and see the editing of the greeting text:

Editing the welcome text

Let's look at the set parameters. Click the menu button and select the single item “Show current settings”. Start the second activity in which we will see the values ​​of our configuration parameters:

image

It's all. As you can see, it is really easy. Good luck!

Original: Android Quick Preferences Tutorial

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


All Articles