Android: Preferences and user settings data

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

CE881: Mobile and Social Application Programming Simon M. Lucas Quiz, Walkthrough, Exercise, Lifecycles, Intents.
CE881: Mobile and Social Application Programming Simon M. Lucas Menus and Dialogs.
Cosc 5/4730 Android: “Dynamic” data.. Saving Dynamic data. While there are a lot of ways to save data – Via the filesystem, database, etc. You can also.
Cosc 5/4730 Game Design. A short game design primer. A game or animation is built on an animation loop. – Instance variables of “objects” are updated.
Programming with Android: Activities
All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
The Android Activity Lifecycle. Slide 2 Introduction Working with the Android logging system Rotation and multiple layouts Understanding the Android activity.
Cosc 5/4730 Game Design. A short game design primer. A game or animation is built on an animation loop. – Instance variables of “objects” are updated.
Cosc 4730 Android Dialogs and notifications. Notifications There are a couple of ways to notify users without interrupting what they are doing The first.
Cosc 4730 Android TabActivity and ListView. TabActivity A TabActivity allows for multiple “tabs”. – Each Tab is it’s own activity and the “root” activity.
Android Development (Basics)
Data Storage: Part 1 (Preferences)
Android Fragments A very brief introduction Android Fragments1.
Chien-Chung Shen Manifest and Activity Chien-Chung Shen
Cosc 5/4730 A little on threads and Messages: Handler class.
Better reference the original webpage :
Cosc 5/4730 Information, Resources, and basic GUI concepts.
ANDROID UI – FRAGMENTS. Fragment  An activity is a container for views  When you have a larger screen device than a phone –like a tablet it can look.
Lecture Series on Android Programming Lecturer: Prof.Luqun Li Teaching Assistants: Fengyou Sun, Haijun Yang, Ting.
Cosc 5/4730 Introduction: Threads, Android Activities, and MVC.
Cosc 5/4730 Android Content Providers and Intents.
Cosc 5/4730 Broadcast Receiver. Broadcast receiver A broadcast receiver (short receiver) – is an Android component which allows you to register for system.
Mobile Programming Lecture 6
DUE Hello World on the Android Platform.
Understand applications and their components activity service broadcast receiver content provider intent AndroidManifest.xml.
Data persistence How to save data using SharedPreferences, Files, and SQLite database 1Data persistence.
Android – Fragments L. Grewe.
Cosc 5/4730 Dialogs and below 3.0 and above (fragment)
Networking: Part 1 (Web Content). Networking with Android Android provides A full-featured web browser based on Chromium, the open source browser engine.
Cosc 4730 Android Fragments. Fragments You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own.
Android Boot Camp Demo Application – Part 1. Development Environment Set Up Download and install Java Development Kit (JDK) Download and unzip Android.
Mobile Programming Lecture 7 Dialogs, Menus, and SharedPreferences.
Android: “Dynamic” data and Preferences data.
Android Application Lifecycle and Menus
1 Android Development Lean and mean introduction Based on a presentation by Mihail L. Sichitiu.
Cosc 5/4735 Voice Actions Voice Interactions (API 23+)
Lecture 5: Location Topics: Google Play Services, Location API Date: Feb 16, 2016.
School of Engineering and Information and Communication Technology KIT305/KIT607 Mobile Application Development Android OS –Permissions (cont.), Fragments,
Android Fragments. Slide 2 Lecture Overview Getting resources and configuration information Conceptualizing the Back Stack Introduction to fragments.
Cosc 5/4730 Support design library. Support Design library Adds (API 9+) back support to a number of 5.0 lollipop widgets and material design pieces –
Fragments and Menus Chapter 4 1. Objectives Learn three different types of menus: options, context, and popup Learn to configure the ActionBar and Toolbar.
Menus. Menus are a common user interface component in many types of applications. The options menu is the primary collection of menu items for an activity.
Cosc 4735 Nougat API 24+ additions.
Introduction to android
Google VR (gvr) CardBoard and DayDream With OpenGL
Location-Based Services: Part 2 (Google Maps)
Activity and Fragment.
CARA 3.10 Major New Features
Android – Event Handling
Android Studio, Android System Basics and Git
Activities, Fragments, and Events
Fragment ?.
CS499 – Mobile Application Development
Android Activities An application can have one or more activities, where Each activity Represents a screen that an app present to its user Extends the.
The Android Activity Lifecycle
Mobile Application Development BSCS-7 Lecture # 11
Android 15: Settings Kirk Scott.
Android – Fragments L. Grewe.
ANDROID UI – FRAGMENTS UNIT II.
Activities and Intents
Barb Ericson Georgia Institute of Technology Oct 2005
Tonga Institute of Higher Education
Constructors, GUI’s(Using Swing) and ActionListner
Mobile Programming Gestures in Android.
Cosc 4730 An Introduction.
Activities and Fragments
Cosc 5/4730 EmojiCompat library..
Preference Activity class
Activities, Fragments, and Intents
Presentation transcript:

Android: Preferences and user settings data Cosc 5/4730 Android: Preferences and user settings data

Preferences It’s normally a good idea to allow a user to setup some preferences for an application Example: Username It’s saved data between runs about how the application should run. This adds a level of professionalism as well to the app, since the preferences are handle just same as preferences for the rest of device, including look and feel. Android provides a preferenceActivity and PreferenceFragment to do this And in v7 and v14 support libraries, now androidx.legacy:legacy-preference At this point, the support libraries are not really needed, since it was to support API 14 and below and we are at API 19.

Preferences (2) The bulk of the work is in the xml document The preferenceActivity and perference fragment only provide a place to show the xml document. The preferenceActivity is deprecated at API 13+ So we use an activity and preferenceFragment.

PreferenceFragment The code is basically the same, but in a fragment. public class PrefFrag extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource( R.xml.preferences); }

Preferences xml You need to create an xml for the preferences Preferences are kept be application sessions by default. <PreferenceScreen …> <PreferenceCategory …> … in-line preference </PreferenceCategory> … </PreferenceCategory> </PreferenceScreen>

CheckBoxPerference On (true) or off (false) <CheckBoxPreference android:key="checkbox_preference“ key used by application to find out the value. android:title="Check Box" android:summary="An example of a Check Box" /> Also, you can also set a default value as well. android:defaultValue="false" Ie off by default

EditTextPreference <EditTextPreference android:key="edittext_preference" android:title="EditText Preference“ android:defaultValue="" android:summary="Example of EditText Dialog" android:dialogTitle="Enter your Name" />

ListPreference <ListPreference /> android:entries="@array/entries_list_preference" android:entryValues="@array/entryvalues_list_preference" android:dialogTitle="list preference example“ android:summary="List preference demo" android:key="list_preference" android:title="list perference" />

Arrays and xml In the values directory created a file called “arrays.xml” <resources> <string-array name="entries_list_preference"> <item>Alpha Option 01</item> <item>Beta Option 02</item> item>Charlie Option 03</item> </string-array> <string-array name= "entryvalues_list_preference"> <item>alpha</item> <item>beta</item> <item>charlie</item> </string-array> </resources>

Switch preference It's a toggle <SwitchPreference android:key="switch_key" android:title="switch Preference" android:defaultValue="true" /> Note this is available in androidx, but in v7 is switchprefencecompat

Multiselect Arrays.xml file <MultiSelectListPreference android:dialogTitle="Multi Select Dialog" android:key="multiselect_key" android:summary="Does this show?" android:title="Multi Select Title" android:entries="@array/weekdays" android:entryValues= "@array/weekdays_values" android:defaultValue= "@array/empty_array" /> Arrays.xml file <string-array name="weekdays"> <item>Monday</item> <item>Tuesday</item> <item>Wednesday</item> </string-array> <string-array name="weekdays_values"> <item>Mon</item> <item>Tue</item> <item>Wed</item> <string-array name="empty_array">

Next screen Create a separation of settings, but using the same xml doc. <PreferenceScreen android:key="screen_preference" android:summary="Check here for another Preference Screen" android:title="Next Preference Screen"> You can place more preferences here that will be shown on the next screen. <CheckBoxPreference android:key= "next_screen_checkbox_preference" android:summary="Next Screen Check Box Demo, but in the same xml" android:title="Next Screen Check Box" /> … more preferences here </PreferenceScreen>

Access the preference In your java code, likely in onResume(…) onResume is called when you app gets the screen back from the preferences screen! Also called when the application starts. code look something like this: SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences (getBaseContext()); Now you get the preferences with abstract Map<String, ?> getAll() OR getBoolean(key, defaultvalue), getInt(key,defvalue), getString(key, defaultvalue), …

preference example prefs is declared on last slide boolean useSensor = prefs.getBoolean(“sensorPref” , false); get the sensorPref key, if not found, default is false. string text = prefs.getString(“textPref”, “”); string list = prefs.getString(“list_preference”,””); Note, if you had set integer or floats as the entryValues, then you want to get them as getInt or getFloat.

MultiSelectList preference values. Getting the values from a multiselectListPreference. mMultiSelectListPreference = (MultiSelectListPreference) getPreferenceScreen().findPreference("multiselect_key"); This returns a Set<String> with the name listed which were selected. Note, you can't guarantee order in the set. This will create a simple string, for the summary. String list = ""; Set<String> selections = mMultiSelectListPreference.getSharedPreferences() .getStringSet("multiselect_key", null); for(String s: selections) { list += s + " "; } mMultiSelectListPreference.setSummary("selection is " + list );

Compatibility (without fragments) getSupportFragmentManager().beginTransaction().replace(android.R. id.content, new PrefFrag()).commit(); android.R.id.content allows you to display the fragment even if you are not using fragments.

Example code The PreferenceDemo has the code from all in. myPreferenceFragment shows everything covered so far. PreferenceupdateFragment show the next stuff Where we have "live" updates of the data.

Preferences android:summary It maybe that instead of you want a the current value listed, instead of the descriptions as I have listed here. You will need to implement a listener in PreferenceFragment called OnSharedPreferenceChangeListener See the dialog example for how to implement the code.

Code Setup some variables in onCreate(…) of the fragment. // Get a reference to the preferences, so we can dynamically update the preference screen summary info. Example from the code example: mEditTextPreference = (EditTextPreference)getPreferenceScreen().findPreference("textPref"); mListPreference = (ListPreference)getPreferenceScreen().findPreference("list_preference"); Implement the OnSharedPreferenceChangeListener in the fragment @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals("textPref")) { //where textPref is the key used in the xml. mEditTextPreference.setSummary( "Text is " + sharedPreferences.getString("textPref", "Default")); } else if (key.equals("list_prefrence")) { mListPreference.setSummary("Current value is " + sharedPreferences.getString(key, "Default")); }

Code (2) Setup to read and setup the summary fields in the onResume() and setup the listener. Remove the listener in the onPause()

preferences xml Only covered a good subset of the preferences xml, but this is not a complete list. see http://developer.android.com/reference/android/preference/Prefere nce.html for more information.

Support libraries

A note The support preference libraries were setup so api 8+ would support all the new preferences that happened in API 14. We are now support API 16+ (API 19+ in this class, Fall 18) So the support are basically legacy at this point. Androidx even uses the legacy name.

Support preference Support preference setup Compile in compile 'com.android.support:preference-v7:25.4.0' (or newer). LIKELY DON'T USE THIS ONE iff not using any v14 features, like multiselectperference OR compile 'com.android.support:preference-v14:25.4.0' (or newer) implementation 'androidx.legacy:legacy-preference-v14:1.0.0' Which allows you to use v7 support as well. Almost everything works the same. PreferenceFragmentCompat (v7 version and a supportFragment) PreferenceFragment (v14, not a supportFragment), so use the PreferenceFragmentCompat. Not you can use v14 features like the multiselect in a v7. It's about the phone's APIs at that point. You also need to add theme to the style.xml or it will force close. <item name="preferenceTheme">@style/PreferenceThemeOverlay</item>

Support preference (2) One major difference Next screen preferences. The support doesn't not handle it for you, like the standard will. We need to implement a OnPreferenceStartScreenCallback and use the "rootKey" value for the screen in the activity controlling the preferencefragmentCompat The only change in the fragment change from add, to set and use the rookey setPreferencesFromResource(R.xml.preferences, rootKey); Any change listeners for summary fields remain unchanged.

OnPreferenceStartScreenCallback Using the implements PreferenceFragment.OnPreferenceStartScreenCallback (compat as needed) Then the overriding code and the next screen will work in the support library. public boolean onPreferenceStartScreen(PreferenceFragment preferenceFragment, PreferenceScreen preferenceScreen) { first get the new rootkey (ie, moving to the next screen, so which one if more then one. Bundle args = new Bundle(); args.putString(PreferenceFragment.ARG_PREFERENCE_ROOT, preferenceScreen.getKey()); //get the new root key now add that to the fragmenet PrefFrag fragment = new PrefFrag(); fragment.setArguments(args); now show the new fragment. FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(android.R.id.content, fragment, preferenceScreen.getKey()); ft.addToBackStack(preferenceScreen.getKey()); ft.commit(); return true; }

supportPreferenceDemo Demos a all the same as the preferenceDemo. myPreferenceActivity and myPreferenceFragment are preferenceFragmentCompat With the onpreferencestartscreen callbacks PreferenceupdateFragment has the summary code in the fragment Note the example will use myPreferenceFragment in the MainActivity and the myPreferenceActivity to show how just use them without a framelayout.

References http://developer.android.com/reference/android/preference/PreferenceActivity.html http://developer.android.com/reference/android/preference/PreferenceFragment.html http://stackoverflow.com/questions/7112706/preferencefragment-alternative-for-the- android-compatibility-api http://android-er.blogspot.com/2012/07/example-of-using-preferencefragment.html http://gmariotti.blogspot.com/2013/01/preferenceactivity-preferencefragment.html http://www.cs.dartmouth.edu/~campbell/cs65/lecture12/lecture12.html https://stackoverflow.com/questions/32487206/inner-preferencescreen-not-opens-with- preferencefragmentcompat and the github example code at https://github.com/madlymad/PreferenceApp

Q A &