SlideShare a Scribd company logo
1 of 54
Android - Localization
Localization
• The way of changing string into different
languages is called as localization.
Why?
• An android application can run on many
devices in many different regions.
• In order to make your application more
interactive, your application should handle
text,numbers, files e.t.c in ways appropriate to
the locales where your application will be
used.
How?
• Idea
– Change the display based on the user’s language
• Resources that typically change
– Strings (in res/values, e.g., in res/values/strings.xml)
– Images (in res/drawable – image file or XML file)
– Colors (in res/values, e.g., in res/values/colors.xml)
– Audio and video (in res/raw)
– Dimensions, arrays, and styles (in res/values, e.g.,
…/dimens.xml, …/arrays.xml, …/styles.x ml)
Steps
• Make multiple folders with language codes
– res/values, res/values-es, res/values-ja, etc.
• Language codes are specified by ISO 639-1
– http://en.wikipedia.org/wiki/ISO_639-1
• Define all strings in default folder
– In res/values, define all names
Use the most common language
– E.g., res/values/strings.xml (or other name in res/values)
<string name="company_name">Apple</string>
<string name="welcome_message">Welcome!</string>
• Use similar approach for colors, images, etc.
– Use res/values/ for all colors, dimensions, arrays, etc.
– Use res/drawable for all image files
– Use res/raw for all audio and video files11
Steps (Continued)
• Put language-specific strings in language-
specific folders
– In res/values-es/strings.xml (or res/values-ja, etc), redefine only
the names that change based on language
– E.g., in res/values-es/strings.xml
<string name="welcome_message">¡Bienvenidos!</string>
– No entry for company_name, since the company name does not
change (in Spanish, it is still Apple, not Manzana)
– E.g., in res/values-ja/strings.xml
<string name="welcome_message">ようこそ!</string>
– No entry for company_name, since the company name does not
change (in Japanese, it is still Apple, not アップル)
• Use similar approach for other resources
– res/values-es/colors.xml, res/drawable-es/flag.png, etc.
• Only redefine the ones that change based on language
Steps (Continued)
• In XML, refer to base string name
– someAttribute="@string/company_name"
– someAttribute="@ string/welcome_message"
• No reference to folder or language.
• Android will provide the proper version automatically. It first
loads values from res/values/strings.xml, then loads values
from res/values-es/strings.xml. Any names in second file that
are common to first file are replaced.
• In Java, refer to base string name
– getString(R.string.company_name)
– getString(R.string.welcome_message)
• No reference to folder or language. Same process as above.
• Use similar approach for other resources
– XML: @drawable/flag, @color/default_foreground, etc.
– Java: R.drawable.flag, R.color.default_foreground, etc.
Number Format
• NumberFormat is the abstract base class for
all number formats. This class provides the
interface for formatting and parsing numbers.
• NumberFormat also provides methods for
determining which locales have number
formats, and what their names are.
• NumberFormat helps you to format and parse
numbers for any locale.
Number Format
• To format a number for the current Locale,
use one of the factory class methods:
myString =NumberFormat.getInstance().format(myNumber);
• To format a number for a different Locale,
specify it in the call to getInstance.
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
• You can also use a NumberFormat to parse
numbers:
myNumber = nf.parse(myString);
Number Format
• Use getInstance or getNumberInstance to get
the normal number format.
• Use getIntegerInstance to get an integer
number format.
• Use getCurrencyInstance to get the currency
number format.
• And use getPercentInstance to get a format
for displaying percentages. With this format, a
fraction like 0.53 is displayed as 53%.
Date Format
• DateFormat provides many class methods for
obtaining default date/time formatters based
on the default or a given locale and a number
of formatting styles.
• DateFormat helps you to format and parse
dates for any locale. Your code can be
completely independent of the locale
conventions for months, days of the week, or
even the calendar format: lunar vs. solar.
Date Format
• To format a date for the current Locale, use
one of the static factory methods:
myString = DateFormat.getDateInstance().format(myDate);
• To format a date for a different Locale, specify
it in the call to getDateInstance().
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG,
Locale.FRANCE);
• You can use a DateFormat to parse also.
myDate = df.parse(myString);
Date Format
• Use getDateInstance to get the normal date
format for that country. There are other static
factory methods available.
• Use getTimeInstance to get the time format for
that country.
• Use getDateTimeInstance to get a date and time
format.
• You can pass in different options to these factory
methods to control the length of the result; from
SHORT to MEDIUM to LONG to FULL
Date Format
• The exact result depends on the locale, but
generally:
• SHORT is completely numeric, such as
12.13.52 or 3:30pm
• MEDIUM is longer, such as Jan 12, 1952
• LONG is longer, such as January 12, 1952 or
3:30:32pm
• FULL is pretty completely specified, such as
Tuesday, April 12, 1952 AD or 3:30:42pm PST.
Date Format
• You can also set the time zone on the format if
you wish.
• Use SimpleDateFormat If you want even more
control over the format or parsing.
DEMO TIME
RTL(right-to-left)
WHY RTL?
• Few languages such as Arabic, Hebrew, or
Persian are written from Right to Left.
– To handle them, Android supports RTL layouts from API
17+ i.e., Android 4.2 (Jelly Bean)
RTL in Android
• Android provides a feature to make our APP
bidirectional(LTR & RTL). This feature was introduced
in android 4.1 (Jelly Bean) for TextView and EditText
elements, allowing apps to display and edit text in
both left-to-right (LTR) and right-to-left (RTL).
• There was full support for RTL feature in android 4.2
version. It makes the exact mirror image of our
existing layout.
RTL…
Android 4.2 includes the following APIs to
help manage View components:
– android:layoutDirection — attribute for setting
the direction of a component’s layout.
– android:textDirection — attribute for setting the
direction of a component’s text.
– android:textAlignment — attribute for setting the
alignment of a component’s text.
– getLayoutDirectionFromLocale() — method for
getting the Locale-specified direction
Steps
• add- android:supportsRtl="true" to the <application>
element in manifest file.
• Change all of app’s “left/right” layout properties to
new “start/end” equivalents.
– If you are targeting your app to Android 4.2 (the app’s
targetSdkVersion or minSdkVersion is 17 or higher), then
you should use “start” and “end” instead of “left” and
“right”. For example,android:paddingLeft should
become android:paddingStart
– If you want your app to work with versions earlier than
Android 4.2 (the app’s targetSdkVersion orminSdkVersion
is 16 or less), then you should add “start” and end” in
addition to “left” and “right”. For example, you’d use both
android:paddingLeft and android:paddingStar
Steps (Continued)
Or
If you are using Android studio then open your
project in Android Studio and follow the steps:
• Click on “Refactor” in android studio’s menu bar.
• There will be a pop with options, reach to the end
of the menu and click on “Add RTL Support
where possible”.
• Now, you will get a popup. Tick the checkbox
accordingly.
Localization checklist
Research
target
languages and
locales
Use Google
Play data to
find
localization
opportunities
Design your
app for
localization
Optimize your
app if you’re
targeting
emerging
markets.
Localization checklist
Manage your
app’s U strings
Translate your
app, store
listing, and
other
resources
Test your
localized app
Run a beta
test
Localization checklist
Plan for
international
marketing
Final checks
and
publishing
Browse and
reply to user
reviews
Run store
listing
experiments
Android Shared Preferences
Android Shared Preferences
• Shared Preferences allows activities and
applications to keep preferences, in the form
of key-value pairs similar to a Map that will
persist even when the user closes the
application.
• Android stores Shared Preferences settings as
XML file in shared_prefs folder under
DATA/data/{application package} directory.
SharedPreferences
• SharedPreferences is application specific, i.e.
the data is lost on performing one of the
following options:
– on uninstalling the application
– on clearing the application data (through Settings)
• As the name suggests, the primary purpose is
to store user-specified configuration details,
such as user specific settings, keeping the
user logged into the application.
STEPS
• To get access to the preferences, we have three
APIs to choose from:
– getPreferences() : used from within your Activity, to
access activity-specific preferences
– getSharedPreferences() : used from within your
Activity (or other application Context), to access
application-level preferences
– getDefaultSharedPreferences() : used on the
PreferenceManager, to get the shared preferences
that work in concert with Android’s overall preference
framework
STEPS
• In this tutorial we’ll go with
getSharedPreferences(). The method is
defined as follows:
• getSharedPreferences (String PREFS_NAME,
int mode)
– PREFS_NAME is the name of the file.
– mode is the operating mode.
MODE
• MODE_PRIVATE: the default mode, where the created file can only
be accessed by the calling application
• MODE_WORLD_READABLE: Creating world-readable files is very
dangerous, and likely to cause security holes in applications
• MODE_WORLD_WRITEABLE: Creating world-writable files is very
dangerous, and likely to cause security holes in applications
• MODE_MULTI_PROCESS: This method will check for modification of
preferences even if the Shared Preference instance has already
been loaded
• MODE_APPEND: This will append the new preferences with the
already existing preferences
• MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag.
When it is set, it would enable write ahead logging by default
Initialization
• We need an editor to edit and save the
changes in shared preferences. The following
code can be used to get the shared
preferences.
– SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for
private mode
– Editor editor = pref.edit()
Storing Data
• editor.commit() is used in order to save changes to shared
preferences.
– editor.putBoolean("key_name", true); // Storing boolean -
true/false
– editor.putString("key_name", "string value"); // Storing string
– editor.putInt("key_name", "int value"); // Storing integer
– editor.putFloat("key_name", "float value"); // Storing float
– editor.putLong("key_name", "long value"); // Storing long
– editor.commit(); // commit changes
– editor.apply(); // it will commit your changes back from
editor to the sharedPreference object you are calling
Retrieving Data
• Data can be retrieved from saved preferences by
calling getString() as follows:
– pref.getString("key_name", null); // getting String
– pref.getInt("key_name", null); // getting Integer
– pref.getFloat("key_name", null); // getting Float
– pref.getLong("key_name", null); // getting Long
– pref.getBoolean("key_name", null); // getting
boolean
Clearing or Deleting Data
• remove(“key_name”) is used to delete that
particular value.
• clear() is used to remove all data
– editor.remove("name"); // will delete key name
– editor.remove("email"); // will delete key email
– editor.commit(); // commit changes
– editor.clear();
– editor.commit(); // commit changes
DEMO TIME
Preferences Settings
Implementing Preferences Settings
• We often see Settings screen in many android
apps through which you can configure the app
preferences on your choice.
• For example you wanna change the
notification sound or turn off notification
messages from the app settings.
Preferences Settings
• Normally people manually develop their own
UI for settings and manage the values in
shared preferences, not awaring the fact that
android do provide APIs specific to Settings
Preferences to achieve the same in a robust
way.
• In this section we are going to learn how to
implement the settings screen considering the
various combinations of settings items.
Preferences Settings
• Instead of using View objects to build the user
interface, settings are built using various subclasses of
the Preference class that you declare in an XML file.
• A Preference object is the building block for a single
setting.
• Each Preference appears as an item in a list and
provides the appropriate UI for users to modify the
setting. For example, a CheckBoxPreference creates a
list item that shows a checkbox, and a ListPreference
creates an item that opens a dialog with a list of choices.
Preferences Settings
• Each Preference you add has a corresponding
key-value pair that the system uses to save the
setting in a default SharedPreferences file for
your app's settings.
• When the user changes a setting, the system
updates the corresponding value in the
SharedPreferences file for you.
• The only time you should directly interact with
the associated SharedPreferences file is when you
need to read the value in order to determine
your app's behavior based on the user's setting.
Preferences Settings
• Because our app's settings UI is built using
Preference objects instead of View objects, we
need to use a specialized Activity or Fragment
subclass to display the list settings:
• If your app supports versions of Android older
than 3.0 (API level 10 and lower), you must
build the activity as an extension of the
PreferenceActivity class.
Defining Preferences in XML
Attributes details
android:key
• This attribute is required for preferences that persist a data
value. It specifies the unique key (a string) the system uses
when saving this setting's value in the SharedPreferences.
android:title
• This provides a user-visible name for the setting.
android:defaultValue
• This specifies the initial value that the system should set in
the SharedPreferences file. You should supply a default
value for all settings.
Creating a Preference Activity
• To display your settings in an activity, extend
the PreferenceActivity class.
• This is an extension of the traditional Activity
class that displays a list of settings based on a
hierarchy of Preference objects.
• The PreferenceActivity automatically persists
the settings associated with each Preference
when the user makes a change.
Creating a Preference Activity
• The most important thing to remember is that you do not load
a layout of views during the onCreate() callback.
• Instead, you call addPreferencesFromResource() to add the
preferences you've declared in an XML file to the activity. For
example, here's the bare minimum code:
Reading Preferences
• This is actually enough code for some apps,
because as soon as the user modifies a
preference, the system saves the changes to a
default SharedPreferences file that your other
app components can read when you need to
check the user's settings.
• Many apps, however, require a little more
code in order to listen for changes that occur
to the preferences.
Reading Preferences
All your app's preferences are saved to a file
that's accessible from anywhere within your
app by calling the static method
PreferenceManager.getDefaultSharedPrefere
nces().
This returns the SharedPreferences object
containing all the key-value pairs that are
associated with the Preference objects used in
your PreferenceActivity.
Listening for preference changes
• There are several reasons you might want to be notified as
soon as the user changes one of the preferences.
• In order to receive a callback when a change happens to any
one of the preferences, implement the
SharedPreference.OnSharedPreferenceChangeListener
interface and register the listener for the SharedPreferences
object by calling
registerOnSharedPreferenceChangeListener().
• The interface has only one callback method,
onSharedPreferenceChanged(), and you might find it easiest
to implement the interface as a part of your activity.
Listening for preference changes
Register and Unregister in Callback
@Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
Caution:
• When you call
registerOnSharedPreferenceChangeListener(),
the preference manager does not currently store
a strong reference to the listener.
• You must store a strong reference to the listener,
or it will be susceptible to garbage collection.
• Keep a reference to the listener in the instance
data of an object that will exist as long as you
need the listener.
References
https://developer.android.com/guide/topics/resources
/localization
https://developer.android.com/reference/java/text/Da
teFormat
https://developer.android.com/reference/java/text/Nu
mberFormat
https://developer.android.com/training/data-
storage/shared-preferences
https://developer.android.com/guide/topics/ui/setting
s
https://android.jlelse.eu/rtl-support-on-android-here-
is-all-you-need-know-e13f2df512e2
Thank You 

More Related Content

What's hot

Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application Madhuri Kavade
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaGlenn Guden
 
Introduction to Python Programming language.pptx
Introduction to Python Programming language.pptxIntroduction to Python Programming language.pptx
Introduction to Python Programming language.pptxBharathYusha1
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
Android studio 2.0: default project structure
Android studio 2.0: default project structureAndroid studio 2.0: default project structure
Android studio 2.0: default project structureVyara Georgieva
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python Home
 
Data types in php
Data types in phpData types in php
Data types in phpilakkiya
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android FragmentsSergi Martínez
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesecosio GmbH
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in PythonSujith Kumar
 

What's hot (20)

Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
SQLite database in android
SQLite database in androidSQLite database in android
SQLite database in android
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
 
Python-Polymorphism.pptx
Python-Polymorphism.pptxPython-Polymorphism.pptx
Python-Polymorphism.pptx
 
Introduction to Python Programming language.pptx
Introduction to Python Programming language.pptxIntroduction to Python Programming language.pptx
Introduction to Python Programming language.pptx
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
GRID VIEW PPT
GRID VIEW PPTGRID VIEW PPT
GRID VIEW PPT
 
Android studio 2.0: default project structure
Android studio 2.0: default project structureAndroid studio 2.0: default project structure
Android studio 2.0: default project structure
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python
 
Data types in php
Data types in phpData types in php
Data types in php
 
Introduction to Android Fragments
Introduction to Android FragmentsIntroduction to Android Fragments
Introduction to Android Fragments
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Applets in java
Applets in javaApplets in java
Applets in java
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Android Data Persistence
Android Data PersistenceAndroid Data Persistence
Android Data Persistence
 
GUI programming
GUI programmingGUI programming
GUI programming
 

Similar to Localization and Shared Preferences in android

Android App Development 08 : Support Multiple Devices
Android App Development 08 : Support Multiple DevicesAndroid App Development 08 : Support Multiple Devices
Android App Development 08 : Support Multiple DevicesAnuchit Chalothorn
 
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architectureAndroid Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architectureNicheTech Com. Solutions Pvt. Ltd.
 
03 android application structure
03 android application structure03 android application structure
03 android application structureSokngim Sa
 
Android project architecture
Android project architectureAndroid project architecture
Android project architectureSourabh Sahu
 
Android application development fundamentals
Android application development fundamentalsAndroid application development fundamentals
Android application development fundamentalsindiangarg
 
Castle in the Clouds: SaaS-Enabling Oracle ADF Faces Applications
Castle in the Clouds: SaaS-Enabling Oracle ADF Faces ApplicationsCastle in the Clouds: SaaS-Enabling Oracle ADF Faces Applications
Castle in the Clouds: SaaS-Enabling Oracle ADF Faces ApplicationsLucas Jellema
 
SE-IT JAVA LAB OOP CONCEPT
SE-IT JAVA LAB OOP CONCEPTSE-IT JAVA LAB OOP CONCEPT
SE-IT JAVA LAB OOP CONCEPTnikshaikh786
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven DesignLalit Kale
 
walkmod - JUG talk
walkmod - JUG talkwalkmod - JUG talk
walkmod - JUG talkwalkmod
 
I18n design approach for global enterprise platforms
I18n design approach for global enterprise platformsI18n design approach for global enterprise platforms
I18n design approach for global enterprise platformsReddappa Gowd Bandi
 
mobile application development -unit-3-
mobile application development  -unit-3-mobile application development  -unit-3-
mobile application development -unit-3-TejamFandat
 
Custom Metadata Records Deployment From Apex Code
Custom Metadata Records Deployment From Apex CodeCustom Metadata Records Deployment From Apex Code
Custom Metadata Records Deployment From Apex CodeBohdan Dovhań
 
XML, XML Databases and MPEG-7
XML, XML Databases and MPEG-7XML, XML Databases and MPEG-7
XML, XML Databases and MPEG-7Deniz Kılınç
 
Data Science - Part II - Working with R & R studio
Data Science - Part II -  Working with R & R studioData Science - Part II -  Working with R & R studio
Data Science - Part II - Working with R & R studioDerek Kane
 
data structures and its importance
 data structures and its importance  data structures and its importance
data structures and its importance Anaya Zafar
 

Similar to Localization and Shared Preferences in android (20)

Android App Development 08 : Support Multiple Devices
Android App Development 08 : Support Multiple DevicesAndroid App Development 08 : Support Multiple Devices
Android App Development 08 : Support Multiple Devices
 
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architectureAndroid Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
 
Introduction to Visual Basic
Introduction to Visual Basic Introduction to Visual Basic
Introduction to Visual Basic
 
03 android application structure
03 android application structure03 android application structure
03 android application structure
 
Android project architecture
Android project architectureAndroid project architecture
Android project architecture
 
Android application development fundamentals
Android application development fundamentalsAndroid application development fundamentals
Android application development fundamentals
 
Golang online course
Golang online courseGolang online course
Golang online course
 
Castle in the Clouds: SaaS-Enabling Oracle ADF Faces Applications
Castle in the Clouds: SaaS-Enabling Oracle ADF Faces ApplicationsCastle in the Clouds: SaaS-Enabling Oracle ADF Faces Applications
Castle in the Clouds: SaaS-Enabling Oracle ADF Faces Applications
 
SE-IT JAVA LAB OOP CONCEPT
SE-IT JAVA LAB OOP CONCEPTSE-IT JAVA LAB OOP CONCEPT
SE-IT JAVA LAB OOP CONCEPT
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Technical Interview
Technical InterviewTechnical Interview
Technical Interview
 
walkmod - JUG talk
walkmod - JUG talkwalkmod - JUG talk
walkmod - JUG talk
 
I18n design approach for global enterprise platforms
I18n design approach for global enterprise platformsI18n design approach for global enterprise platforms
I18n design approach for global enterprise platforms
 
mobile application development -unit-3-
mobile application development  -unit-3-mobile application development  -unit-3-
mobile application development -unit-3-
 
R programming Language
R programming LanguageR programming Language
R programming Language
 
Custom Metadata Records Deployment From Apex Code
Custom Metadata Records Deployment From Apex CodeCustom Metadata Records Deployment From Apex Code
Custom Metadata Records Deployment From Apex Code
 
XML, XML Databases and MPEG-7
XML, XML Databases and MPEG-7XML, XML Databases and MPEG-7
XML, XML Databases and MPEG-7
 
Data Science - Part II - Working with R & R studio
Data Science - Part II -  Working with R & R studioData Science - Part II -  Working with R & R studio
Data Science - Part II - Working with R & R studio
 
data structures and its importance
 data structures and its importance  data structures and its importance
data structures and its importance
 
Mobile Application Development class 002
Mobile Application Development class 002Mobile Application Development class 002
Mobile Application Development class 002
 

Recently uploaded

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

Localization and Shared Preferences in android

  • 2. Localization • The way of changing string into different languages is called as localization.
  • 3. Why? • An android application can run on many devices in many different regions. • In order to make your application more interactive, your application should handle text,numbers, files e.t.c in ways appropriate to the locales where your application will be used.
  • 4. How? • Idea – Change the display based on the user’s language • Resources that typically change – Strings (in res/values, e.g., in res/values/strings.xml) – Images (in res/drawable – image file or XML file) – Colors (in res/values, e.g., in res/values/colors.xml) – Audio and video (in res/raw) – Dimensions, arrays, and styles (in res/values, e.g., …/dimens.xml, …/arrays.xml, …/styles.x ml)
  • 5. Steps • Make multiple folders with language codes – res/values, res/values-es, res/values-ja, etc. • Language codes are specified by ISO 639-1 – http://en.wikipedia.org/wiki/ISO_639-1 • Define all strings in default folder – In res/values, define all names Use the most common language – E.g., res/values/strings.xml (or other name in res/values) <string name="company_name">Apple</string> <string name="welcome_message">Welcome!</string> • Use similar approach for colors, images, etc. – Use res/values/ for all colors, dimensions, arrays, etc. – Use res/drawable for all image files – Use res/raw for all audio and video files11
  • 6. Steps (Continued) • Put language-specific strings in language- specific folders – In res/values-es/strings.xml (or res/values-ja, etc), redefine only the names that change based on language – E.g., in res/values-es/strings.xml <string name="welcome_message">¡Bienvenidos!</string> – No entry for company_name, since the company name does not change (in Spanish, it is still Apple, not Manzana) – E.g., in res/values-ja/strings.xml <string name="welcome_message">ようこそ!</string> – No entry for company_name, since the company name does not change (in Japanese, it is still Apple, not アップル) • Use similar approach for other resources – res/values-es/colors.xml, res/drawable-es/flag.png, etc. • Only redefine the ones that change based on language
  • 7. Steps (Continued) • In XML, refer to base string name – someAttribute="@string/company_name" – someAttribute="@ string/welcome_message" • No reference to folder or language. • Android will provide the proper version automatically. It first loads values from res/values/strings.xml, then loads values from res/values-es/strings.xml. Any names in second file that are common to first file are replaced. • In Java, refer to base string name – getString(R.string.company_name) – getString(R.string.welcome_message) • No reference to folder or language. Same process as above. • Use similar approach for other resources – XML: @drawable/flag, @color/default_foreground, etc. – Java: R.drawable.flag, R.color.default_foreground, etc.
  • 8. Number Format • NumberFormat is the abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. • NumberFormat also provides methods for determining which locales have number formats, and what their names are. • NumberFormat helps you to format and parse numbers for any locale.
  • 9. Number Format • To format a number for the current Locale, use one of the factory class methods: myString =NumberFormat.getInstance().format(myNumber); • To format a number for a different Locale, specify it in the call to getInstance. NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH); • You can also use a NumberFormat to parse numbers: myNumber = nf.parse(myString);
  • 10. Number Format • Use getInstance or getNumberInstance to get the normal number format. • Use getIntegerInstance to get an integer number format. • Use getCurrencyInstance to get the currency number format. • And use getPercentInstance to get a format for displaying percentages. With this format, a fraction like 0.53 is displayed as 53%.
  • 11. Date Format • DateFormat provides many class methods for obtaining default date/time formatters based on the default or a given locale and a number of formatting styles. • DateFormat helps you to format and parse dates for any locale. Your code can be completely independent of the locale conventions for months, days of the week, or even the calendar format: lunar vs. solar.
  • 12. Date Format • To format a date for the current Locale, use one of the static factory methods: myString = DateFormat.getDateInstance().format(myDate); • To format a date for a different Locale, specify it in the call to getDateInstance(). DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE); • You can use a DateFormat to parse also. myDate = df.parse(myString);
  • 13. Date Format • Use getDateInstance to get the normal date format for that country. There are other static factory methods available. • Use getTimeInstance to get the time format for that country. • Use getDateTimeInstance to get a date and time format. • You can pass in different options to these factory methods to control the length of the result; from SHORT to MEDIUM to LONG to FULL
  • 14. Date Format • The exact result depends on the locale, but generally: • SHORT is completely numeric, such as 12.13.52 or 3:30pm • MEDIUM is longer, such as Jan 12, 1952 • LONG is longer, such as January 12, 1952 or 3:30:32pm • FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST.
  • 15. Date Format • You can also set the time zone on the format if you wish. • Use SimpleDateFormat If you want even more control over the format or parsing.
  • 18. WHY RTL? • Few languages such as Arabic, Hebrew, or Persian are written from Right to Left. – To handle them, Android supports RTL layouts from API 17+ i.e., Android 4.2 (Jelly Bean)
  • 19. RTL in Android • Android provides a feature to make our APP bidirectional(LTR & RTL). This feature was introduced in android 4.1 (Jelly Bean) for TextView and EditText elements, allowing apps to display and edit text in both left-to-right (LTR) and right-to-left (RTL). • There was full support for RTL feature in android 4.2 version. It makes the exact mirror image of our existing layout.
  • 20. RTL… Android 4.2 includes the following APIs to help manage View components: – android:layoutDirection — attribute for setting the direction of a component’s layout. – android:textDirection — attribute for setting the direction of a component’s text. – android:textAlignment — attribute for setting the alignment of a component’s text. – getLayoutDirectionFromLocale() — method for getting the Locale-specified direction
  • 21. Steps • add- android:supportsRtl="true" to the <application> element in manifest file. • Change all of app’s “left/right” layout properties to new “start/end” equivalents. – If you are targeting your app to Android 4.2 (the app’s targetSdkVersion or minSdkVersion is 17 or higher), then you should use “start” and “end” instead of “left” and “right”. For example,android:paddingLeft should become android:paddingStart – If you want your app to work with versions earlier than Android 4.2 (the app’s targetSdkVersion orminSdkVersion is 16 or less), then you should add “start” and end” in addition to “left” and “right”. For example, you’d use both android:paddingLeft and android:paddingStar
  • 22. Steps (Continued) Or If you are using Android studio then open your project in Android Studio and follow the steps: • Click on “Refactor” in android studio’s menu bar. • There will be a pop with options, reach to the end of the menu and click on “Add RTL Support where possible”. • Now, you will get a popup. Tick the checkbox accordingly.
  • 23. Localization checklist Research target languages and locales Use Google Play data to find localization opportunities Design your app for localization Optimize your app if you’re targeting emerging markets.
  • 24. Localization checklist Manage your app’s U strings Translate your app, store listing, and other resources Test your localized app Run a beta test
  • 25. Localization checklist Plan for international marketing Final checks and publishing Browse and reply to user reviews Run store listing experiments
  • 27. Android Shared Preferences • Shared Preferences allows activities and applications to keep preferences, in the form of key-value pairs similar to a Map that will persist even when the user closes the application. • Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory.
  • 28. SharedPreferences • SharedPreferences is application specific, i.e. the data is lost on performing one of the following options: – on uninstalling the application – on clearing the application data (through Settings) • As the name suggests, the primary purpose is to store user-specified configuration details, such as user specific settings, keeping the user logged into the application.
  • 29. STEPS • To get access to the preferences, we have three APIs to choose from: – getPreferences() : used from within your Activity, to access activity-specific preferences – getSharedPreferences() : used from within your Activity (or other application Context), to access application-level preferences – getDefaultSharedPreferences() : used on the PreferenceManager, to get the shared preferences that work in concert with Android’s overall preference framework
  • 30. STEPS • In this tutorial we’ll go with getSharedPreferences(). The method is defined as follows: • getSharedPreferences (String PREFS_NAME, int mode) – PREFS_NAME is the name of the file. – mode is the operating mode.
  • 31. MODE • MODE_PRIVATE: the default mode, where the created file can only be accessed by the calling application • MODE_WORLD_READABLE: Creating world-readable files is very dangerous, and likely to cause security holes in applications • MODE_WORLD_WRITEABLE: Creating world-writable files is very dangerous, and likely to cause security holes in applications • MODE_MULTI_PROCESS: This method will check for modification of preferences even if the Shared Preference instance has already been loaded • MODE_APPEND: This will append the new preferences with the already existing preferences • MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag. When it is set, it would enable write ahead logging by default
  • 32. Initialization • We need an editor to edit and save the changes in shared preferences. The following code can be used to get the shared preferences. – SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode – Editor editor = pref.edit()
  • 33. Storing Data • editor.commit() is used in order to save changes to shared preferences. – editor.putBoolean("key_name", true); // Storing boolean - true/false – editor.putString("key_name", "string value"); // Storing string – editor.putInt("key_name", "int value"); // Storing integer – editor.putFloat("key_name", "float value"); // Storing float – editor.putLong("key_name", "long value"); // Storing long – editor.commit(); // commit changes – editor.apply(); // it will commit your changes back from editor to the sharedPreference object you are calling
  • 34. Retrieving Data • Data can be retrieved from saved preferences by calling getString() as follows: – pref.getString("key_name", null); // getting String – pref.getInt("key_name", null); // getting Integer – pref.getFloat("key_name", null); // getting Float – pref.getLong("key_name", null); // getting Long – pref.getBoolean("key_name", null); // getting boolean
  • 35. Clearing or Deleting Data • remove(“key_name”) is used to delete that particular value. • clear() is used to remove all data – editor.remove("name"); // will delete key name – editor.remove("email"); // will delete key email – editor.commit(); // commit changes – editor.clear(); – editor.commit(); // commit changes
  • 38. Implementing Preferences Settings • We often see Settings screen in many android apps through which you can configure the app preferences on your choice. • For example you wanna change the notification sound or turn off notification messages from the app settings.
  • 39. Preferences Settings • Normally people manually develop their own UI for settings and manage the values in shared preferences, not awaring the fact that android do provide APIs specific to Settings Preferences to achieve the same in a robust way. • In this section we are going to learn how to implement the settings screen considering the various combinations of settings items.
  • 40. Preferences Settings • Instead of using View objects to build the user interface, settings are built using various subclasses of the Preference class that you declare in an XML file. • A Preference object is the building block for a single setting. • Each Preference appears as an item in a list and provides the appropriate UI for users to modify the setting. For example, a CheckBoxPreference creates a list item that shows a checkbox, and a ListPreference creates an item that opens a dialog with a list of choices.
  • 41. Preferences Settings • Each Preference you add has a corresponding key-value pair that the system uses to save the setting in a default SharedPreferences file for your app's settings. • When the user changes a setting, the system updates the corresponding value in the SharedPreferences file for you. • The only time you should directly interact with the associated SharedPreferences file is when you need to read the value in order to determine your app's behavior based on the user's setting.
  • 42. Preferences Settings • Because our app's settings UI is built using Preference objects instead of View objects, we need to use a specialized Activity or Fragment subclass to display the list settings: • If your app supports versions of Android older than 3.0 (API level 10 and lower), you must build the activity as an extension of the PreferenceActivity class.
  • 44. Attributes details android:key • This attribute is required for preferences that persist a data value. It specifies the unique key (a string) the system uses when saving this setting's value in the SharedPreferences. android:title • This provides a user-visible name for the setting. android:defaultValue • This specifies the initial value that the system should set in the SharedPreferences file. You should supply a default value for all settings.
  • 45. Creating a Preference Activity • To display your settings in an activity, extend the PreferenceActivity class. • This is an extension of the traditional Activity class that displays a list of settings based on a hierarchy of Preference objects. • The PreferenceActivity automatically persists the settings associated with each Preference when the user makes a change.
  • 46. Creating a Preference Activity • The most important thing to remember is that you do not load a layout of views during the onCreate() callback. • Instead, you call addPreferencesFromResource() to add the preferences you've declared in an XML file to the activity. For example, here's the bare minimum code:
  • 47. Reading Preferences • This is actually enough code for some apps, because as soon as the user modifies a preference, the system saves the changes to a default SharedPreferences file that your other app components can read when you need to check the user's settings. • Many apps, however, require a little more code in order to listen for changes that occur to the preferences.
  • 48. Reading Preferences All your app's preferences are saved to a file that's accessible from anywhere within your app by calling the static method PreferenceManager.getDefaultSharedPrefere nces(). This returns the SharedPreferences object containing all the key-value pairs that are associated with the Preference objects used in your PreferenceActivity.
  • 49. Listening for preference changes • There are several reasons you might want to be notified as soon as the user changes one of the preferences. • In order to receive a callback when a change happens to any one of the preferences, implement the SharedPreference.OnSharedPreferenceChangeListener interface and register the listener for the SharedPreferences object by calling registerOnSharedPreferenceChangeListener(). • The interface has only one callback method, onSharedPreferenceChanged(), and you might find it easiest to implement the interface as a part of your activity.
  • 51. Register and Unregister in Callback @Override protected void onResume() { super.onResume(); getPreferenceScreen().getSharedPreferences() .registerOnSharedPreferenceChangeListener(this); } @Override protected void onPause() { super.onPause(); getPreferenceScreen().getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(this); }
  • 52. Caution: • When you call registerOnSharedPreferenceChangeListener(), the preference manager does not currently store a strong reference to the listener. • You must store a strong reference to the listener, or it will be susceptible to garbage collection. • Keep a reference to the listener in the instance data of an object that will exist as long as you need the listener.