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.
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.
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.