Android Persistence With Preferences and Files - Tutorial
Android Persistence With Preferences and Files - Tutorial
Android Persistence With Preferences and Files - Tutorial
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
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.
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.
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();
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.
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.
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" >
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...
}
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));
}
TRAINING EVENTS
Cross Mobile App Dev. Schulung
in Hamburg
(https://www.vogella.com/training/appdev
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
}
}
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.
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();
}
}
}
}
Online Training
Onsite Training
(https://learn.vogella.com/) (https://www.vogella.com/training/)
Consulting
(https://www.vogella.com/consulting/)