Android Persistence With Preferences and Files - Tutorial

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

11/11/2019 Android Persistence with preferences and files - Tutorial

Left Center Right

Tutorials (https://www.vogella.com/tutorials/) Training (https://www.vogella.com/training/)


Search
(https://www.vogella.com/)

Android Persistence with


Consulting (https://www.vogella.com/consulting/) Company (https://www.vogella.com/company/)
GET MORE...
Read Premium Content ...

preferences and files -


Contact us (https://www.vogella.com/contact.html)
(https://learn.vogella.com)
Book Onsite Training

Tutorial (https://www.vogella.com/training/onsite/
Consulting
 (https://twitter.com/vogella)Lars Vogel (c) 2014, 2019 vogella GmbH (https://www.vogella.com/consulting/)
 – Version 3.4, 21.09.2018
TRAINING EVENTS
TABLE OF CONTENTS
Cross Mobile App Dev. Schulung
1. File based persistence 
in Hamburg
2. Preferences (https://www.vogella.com/training/appdev

3. Exercise: Prerequisites

4. Exercise: Preference setting for the RSS feed 

5. Android File API 

6. Links and Literature 

Appendix A: Copyright, License and Source code

File based persistence in Android. This tutorial describes how to


save key-value pairs using the preference API in Android. It also
explains how to read and write files in Android.

Thinking About Pet Insurance?


1.9 Million Claims processed in 2018.

1. File based persistence


1.1. Methods of local data persistence

LeftChandlor000022Bio10/11 Center Right


https://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html 1/11
11/11/2019 Android Persistence with preferences and files - Tutorial
Left Center Right

Android allows to persists application data via the file system. For each
Tutorials (https://www.vogella.com/tutorials/) Training
application the Android system Search
(https://www.vogella.com/training/)
creates a data/data/[application package]
(https://www.vogella.com/) directory.

Consulting (https://www.vogella.com/consulting/) Company (https://www.vogella.com/company/)


Android supports the following ways of storing data in the local fileGET MORE...
system:

Read Premium Content ...


Files - You can create and update files
Contact us (https://www.vogella.com/contact.html)
(https://learn.vogella.com)
Preferences - Android allows you to save and retrieve persistent key-value
Book Onsite Training
pairs of primitive data type.
(https://www.vogella.com/training/onsite/
SQLite database - instances of SQLite databases are also stored on theConsulting
local file system. (https://www.vogella.com/consulting/)

Files are saved in the files folder and application settings are saved TRAINING
as XML EVENTS
files in the shared_prefs folder.
Cross Mobile App Dev. Schulung
If your application creates an SQLite database this database is saved in the
in Hamburg
main application directory under the databases folder. (https://www.vogella.com/training/appdev

The following screenshot shows a file system which contains file, cache files
and preferences.

Only the application can write into its application directory. It can create
additional sub-directories in this application directory. For these sub-
directories, the application can grant read or write permissions for other
applications.

1.2. Internal vs. external storage


Android has internal storage and external storage. External storage is not
private and may not always be availale. If, for example, the Android device is
connected with a computer, the computer may mount the external system via
USB and that makes this external storage not avaiable for Android
applications.

1.3. Application on external storage


As of Android 8 SDK level it is possible to define that the application can or
should be placed on external storage. For this set the
android:installLocation to preferExternal or auto.

In this case certain application components may be stored on an encrypted


external mount point. Database and other private data will still be stored in
the internal storage system.

LeftChandlor000023Bio10/11 Center Right


https://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html 2/11
11/11/2019 Android Persistence with preferences and files - Tutorial
Left Center Right

Tutorials (https://www.vogella.com/tutorials/) Training (https://www.vogella.com/training/)


Search
(https://www.vogella.com/)
2. Preferences Company (https://www.vogella.com/company/)
Consulting (https://www.vogella.com/consulting/)
GET MORE...
2.1. Storing key-value pairs
Read Premium Content ...
The SharedPreferences class allows to persists key-value pairs of primitive data
Contact us (https://www.vogella.com/contact.html)
(https://learn.vogella.com)
types in the Android file system.
Book Onsite Training
The PreferenceManager class provides methods to get access to these (https://www.vogella.com/training/onsite/
preferences. The following code shows how to access preferences from aConsulting
certain file (https://www.vogella.com/consulting/)

# getting preferences from a specified file TRAINING


TXT
EVENTS
SharedPreferences settings = getSharedPreferences("Test",
Cross Mobile App Dev. Schulung
Context.MODE_PRIVATE);
in Hamburg
(https://www.vogella.com/training/appdev
Preferences should be created private for the application. They can be
accessed via all application components.

A default store for preferences can be accessed via the


PreferenceManager.getDefaultSharedPreferences(this) method call.
Preference value are accessed via the key and the instance of the
SharedPreferences class, as demonstrated in the following listing.

TXT
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getActivity());
String url = settings.getString("url", "n/a");

To create or change preferences you have to call the edit() method on the
SharedPreferences object. Once you have changed the value you have to
call the apply() method to apply your asynchronously to the file system.

TXT
Editor edit = preferences.edit();
edit.putString("username", "new_value_for_user");
edit.apply();

The usage of the commit() method is discouraged, as it


 write the changes synchronously to the file system.

2.2. Preference Listener


You can listen to changes in the preferences via the
registerOnSharedPreferenceChangeListener() method on
SharedPreferences .

LeftChandlor000024Bio10/11 Center Right


https://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html 3/11
11/11/2019 Android Persistence with preferences and files - Tutorial
Left Center Right

JAVA
SharedPreferences prefs =
Tutorials (https://www.vogella.com/tutorials/) Training (https://www.vogella.com/training/)
PreferenceManager.getDefaultSharedPreferences(this);
Search
(https://www.vogella.com/)
// Instance field for listener
Consulting (https://www.vogella.com/consulting/) Company (https://www.vogella.com/company/)
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs,
GET MORE...
String key) {
Read Premium Content ...
Contact // Your Implementation
us (https://www.vogella.com/contact.html)
} (https://learn.vogella.com)
}; Book Onsite Training
prefs.registerOnSharedPreferenceChangeListener(listener); (https://www.vogella.com/training/onsite/
Consulting
One watch out is that SharedPreferences keeps listeners in a (https://www.vogella.com/consulting/)

WeakHashMap hence listener may be recycled if your code does not hold a
reference to it.
TRAINING EVENTS
Cross Mobile App Dev. Schulung
2.3. User interface for preferences in Hamburg
Android allows you to create XML resource files which describes preference
(https://www.vogella.com/training/appdev
key-values. An instance of PreferenceActivity or PreferenceFragment
can generate an user interface for these files. The user interfaces takes care
of persisting the key-value pairs.

To create a preference resource file of type XML.

Android provides the PreferenceFragment class which simplifies the


creation of an user interface for maintaining preference values. This fragment
can load an XML preference definition file via the method
addPreferencesFromResource() .

3. Exercise: Prerequisites
The following exercise assumes that you have created an Android project with
the top-level package com.example.android.rssfeed. This application has at
least one entry in the toolbar with the R.id.action_settings id. Once this
toolbar entry is selected, an existing fragment is replaced.

4. Exercise: Preference setting for the RSS


feed
In this exercise you allow the user to enter his preferred URL for an RSS feed
via another fragment. This fragment uses a preference xml file to define the
user interface.

4.1. Create preference le


Create an Android XML resource called mypreferences.xml in the xml folder.
Add entries to this file similar to the following listing.

LeftChandlor000025Bio10/11 Center Right


https://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html 4/11
11/11/2019 Android Persistence with preferences and files - Tutorial
Left Center Right

XML
<?xml version="1.0" encoding="utf-8"?>
Tutorials (https://www.vogella.com/tutorials/)
<PreferenceScreen
Training (https://www.vogella.com/training/)
Search
(https://www.vogella.com/) xmlns:android="http://schemas.android.com/apk/res/android" >

Consulting (https://www.vogella.com/consulting/) Company (https://www.vogella.com/company/)


<EditTextPreference
android:key="url"
GET MORE...
android:title="Rss feed URL"
Read Premium Content ...
Contact android:inputType="textUri"/>
us (https://www.vogella.com/contact.html)
<CheckBoxPreference android:title="Aktiv" android:key="active"/>(https://learn.vogella.com)
Book Onsite Training
</PreferenceScreen>
(https://www.vogella.com/training/onsite/
Consulting
4.2. Create settings fragment (https://www.vogella.com/consulting/)
Create the class SettingsFragment . It should extends
PreferenceFragment . This fragment loads the preference file andTRAINING
allows the EVENTS
user to change the values. Cross Mobile App Dev. Schulung
inJAVA
Hamburg
package com.example.android.rssreader;
(https://www.vogella.com/training/appdev
import android.os.Bundle;
import android.preference.PreferenceFragment;

public class SettingsFragment extends PreferenceFragment {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.mypreferences);
}
}

4.3. Connect your settings fragment


Ensure that you open the preference fragment via the
onOptionsItemSelected() method. The relevant code is demonstrated in
the following listing.

JAVA
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// more code...
case R.id.action_settings:
// Launch settings activity
if (getResources().getBoolean(R.bool.twoPaneMode)) {

getFragmentManager().beginTransaction().replace(R.id.detailFragment,
new
SettingsFragment()).commit();
} else {

getFragmentManager().beginTransaction().addToBackStack(null).replace(R
.id
.fragment_container, new
SettingsFragment()).commit();
}
return true;
// more code...
}
// more code...
}

LeftChandlor000026Bio10/11 Center Right


https://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html 5/11
11/11/2019 Android Persistence with preferences and files - Tutorial
Left Center Right

Tutorials (https://www.vogella.com/tutorials/) Training (https://www.vogella.com/training/)


Search
(https://www.vogella.com/)
4.4. Use the preference value to load the RSS feed
Consulting (https://www.vogella.com/consulting/) Company (https://www.vogella.com/company/)
GET MORE...
The following code snippet demonstrates how you can access the preference
value in a method. Read Premium Content ...
Contact us (https://www.vogella.com/contact.html)
(https://learn.vogella.com)
JAVA
// if you use this in a service or activity you can use this Book Onsite Training
// if you use this in a fragment use getActivity() or getContent() as
parameter (https://www.vogella.com/training/onsite/
SharedPreferences settings = Consulting
PreferenceManager.getDefaultSharedPreferences(this);
String url = settings.getString("url", (https://www.vogella.com/consulting/)
"https://www.vogella.com/article.rss");
TRAINING EVENTS
4.5. Validate Cross Mobile App Dev. Schulung
in Hamburg
Run your application. Select from your action bar the Settings action. You
should be able to enter a URL. If you press the back button and press the (https://www.vogella.com/training/appdev
refresh button, ensure that the value of the url preference is used in your
activity.

4.6. Optional: Show the current value in the settings


The following code snippet demonstrates how to show the current value in
the preference screen.

LeftChandlor000027Bio10/11 Center Right


https://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html 6/11
11/11/2019 Android Persistence with preferences and files - Tutorial
Left Center Right

JAVA
package com.example.android.rssreader;
Tutorials (https://www.vogella.com/tutorials/) Training (https://www.vogella.com/training/)
Search
(https://www.vogella.com/) import android.content.SharedPreferences;
import android.os.Bundle;
Consulting (https://www.vogella.com/consulting/) Company (https://www.vogella.com/company/)
import android.preference.EditTextPreference;
import android.preference.Preference;
GET MORE...
import android.preference.PreferenceCategory;
Read Premium Content ...
import android.preference.PreferenceFragment;
Contact us (https://www.vogella.com/contact.html)
(https://learn.vogella.com)
public class SettingsFragment extends PreferenceFragment implements
Book Onsite Training
SharedPreferences.OnSharedPreferenceChangeListener {
(https://www.vogella.com/training/onsite/
@Override Consulting
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); (https://www.vogella.com/consulting/)
addPreferencesFromResource(R.xml.mypreferences);
// show the current value in the settings screen TRAINING EVENTS
for (int i = 0; i <
getPreferenceScreen().getPreferenceCount(); i++) { Cross Mobile App Dev. Schulung
initSummary(getPreferenceScreen().getPreference(i));
}
in Hamburg
} (https://www.vogella.com/training/appdev

@Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}

@Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}

@Override
public void onSharedPreferenceChanged(SharedPreferences
sharedPreferences,
String key) {
updatePreferences(findPreference(key));
}

private void initSummary(Preference p) {


if (p instanceof PreferenceCategory) {
PreferenceCategory cat = (PreferenceCategory) p;
for (int i = 0; i < cat.getPreferenceCount(); i++) {
initSummary(cat.getPreference(i));
}
} else {
updatePreferences(p);
}
}

private void updatePreferences(Preference p) {


if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
p.setSummary(editTextPref.getText());
}
}
}

LeftChandlor000028Bio10/11 Center Right


https://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html 7/11
11/11/2019 Android Persistence with preferences and files - Tutorial
Left Center Right

Tutorials (https://www.vogella.com/tutorials/) Training (https://www.vogella.com/training/)


Search
(https://www.vogella.com/)

Consulting (https://www.vogella.com/consulting/) Company (https://www.vogella.com/company/)


GET MORE...
Read Premium Content ...
Contact us (https://www.vogella.com/contact.html)
(https://learn.vogella.com)
Book Onsite Training
(https://www.vogella.com/training/onsite/
Consulting
(https://www.vogella.com/consulting/)

TRAINING EVENTS
Cross Mobile App Dev. Schulung
in Hamburg
(https://www.vogella.com/training/appdev

5. Android File API


5.1. Using the le API
Access to the file system is performed via the standard java.io classes.
Android provides also helper classes for creating and accessing new files and
directories. For example the getDir(String, int) method would create or
access a directory. The openFileInput(String s) method provides access
to an FileInputStream for the file. The openFileOutput(String s,
Context.MODE_PRIVATE) method provides access to an FileOutputStream
for the file.

All modes except Context.MODE_PRIVATE are deprecated, files should be


private to the application.

LeftChandlor000029Bio10/11 Center Right


https://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html 8/11
11/11/2019 Android Persistence with preferences and files - Tutorial
Left Center Right

The following example shows the API usage.


Tutorials (https://www.vogella.com/tutorials/) Training (https://www.vogella.com/training/)
Search
TXT
(https://www.vogella.com/)
public class Util {
public static void writeConfiguration(Context ctx, String s ) {
Consulting (https://www.vogella.com/consulting/) Company (https://www.vogella.com/company/)
try (FileOutputStream openFileOutput = GET MORE...
ctx.openFileOutput( "config.txt", Context.MODE_PRIVATE);)
{ Read Premium Content ...
Contact us (https://www.vogella.com/contact.html)
(https://learn.vogella.com)
openFileOutput.write(s.getBytes());
} catch (Exception e) { Book Onsite Training
// not handled
(https://www.vogella.com/training/onsite/
}
} Consulting
} (https://www.vogella.com/consulting/)

TRAINING
TXT EVENTS
public void readFileFromInternalStorage(String fileName) {
String eol = System.getProperty("line.separator"); Cross Mobile App Dev. Schulung
try (BufferedReader input = new BufferedReader(new
InputStreamReader( in Hamburg
openFileInput(fileName))); ){ (https://www.vogella.com/training/appdev
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line + eol);
}
} catch (Exception e) {
// we do not care
}
}

5.2. External storage


Android supports also access to an external storage system, e.g., the SD card.
All files and directories on the external storage system are readable for all
applications with the correct permission.

To read from external storage your application need to have the


android.permission.READ_EXTERNAL_STORAGE permission.

To write to the external storage system your application needs the


android.permission.WRITE_EXTERNAL_STORAGE permission. You get the
path to the external storage system via the
Environment.getExternalStorageDirectory() method.

Via the following method call you can check the state of the external storage
system. If the Android device is connected via USB to a computer, external
storage might not be available.

TXT
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED
)

The following shows an example for reading from the external storage
system.

LeftChandlor000030Bio10/11 Center Right


https://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html 9/11
11/11/2019 Android Persistence with preferences and files - Tutorial
Left Center Right

TXT
private void readFileFromSDCard() {
Tutorials (https://www.vogella.com/tutorials/) Training (https://www.vogella.com/training/)
File directory = Environment.getExternalStorageDirectory();
Search
(https://www.vogella.com/) // assumes that a file article.rss is available on the SD card
File file = new File(directory + "/article.rss");
Consulting (https://www.vogella.com/consulting/)
if (!file.exists()) Company
{ (https://www.vogella.com/company/)
throw new RuntimeException("File not found");
GET MORE...
}
Read Premium Content ...
Log.e("Testing", "Starting to read");
Contact us (https://www.vogella.com/contact.html)
BufferedReader reader = null; (https://learn.vogella.com)
try { Book Onsite Training
reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder(); (https://www.vogella.com/training/onsite/
String line; Consulting
while ((line = reader.readLine()) != null) {
builder.append(line); (https://www.vogella.com/consulting/)
}
} catch (Exception e) { TRAINING EVENTS
e.printStackTrace();
} finally { Cross Mobile App Dev. Schulung
if (reader != null) {
in Hamburg
try {
reader.close(); (https://www.vogella.com/training/appdev
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

6. Links and Literature


6.1. Android Resources
Introduction to Android Development
(https://www.vogella.com/tutorials/Android/article.html)

Android Location API and Google Maps


(https://www.vogella.com/tutorials/AndroidLocationAPI/article.html)

Android Homepage (https://www.android.com/intl/de_de/)

https://www.android.com/intl/de_de/ == vogella training and consulting


support

Online Training

Onsite Training
(https://learn.vogella.com/) (https://www.vogella.com/training/)


Consulting
(https://www.vogella.com/consulting/)

Appendix A: Copyright, License and Source


code
LeftChandlor000031Bio10/11 Center Right
https://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html 10/11
11/11/2019 Android Persistence with preferences and files - Tutorial
Left Center Right

Copyright © 2012-2019 vogella GmbH. Free use of the software examples is


Tutorials (https://www.vogella.com/tutorials/)
granted under the terms ofTraining Search
(https://www.vogella.com/training/)
the Eclipse Public License 2.0
(https://www.vogella.com/) (https://www.eclipse.org/legal/epl-2.0). This tutorial is published under the
Creative Commons Attribution-NonCommercial-ShareAlike
Consulting (https://www.vogella.com/consulting/) 3.0 Germany
Company (https://www.vogella.com/company/)
(http://creativecommons.org/licenses/by-nc-sa/3.0/de/deed.en) license. GET MORE...
Read Premium Content ...
Licence (https://www.vogella.com/license.html)
Contact us (https://www.vogella.com/contact.html)
(https://learn.vogella.com)

Source code (https://www.vogella.com/code/index.html) Book Onsite Training


(https://www.vogella.com/training/onsite/
Support free tutorials (https://www.vogella.com/support.html) Consulting
(https://www.vogella.com/consulting/)

Last updated 18:11 04. Nov 2019


TRAINING EVENTS
Cross Mobile App Dev. Schulung
in Hamburg
(https://www.vogella.com/training/appdev

LeftChandlor000032Bio10/11 Center Right


https://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html 11/11

You might also like