0% found this document useful (0 votes)
62 views24 pages

ITE 2152 Introduction To Mobile Application Development: Week 9

The document discusses three primary ways to persist data in Android applications: 1. SharedPreferences for saving small chunks of user preference data in key-value pairs to an XML file. 2. Traditional file systems for saving larger amounts of data like text to internal storage files. 3. SQLite databases for storing structured data in tables using the SQLite interface.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views24 pages

ITE 2152 Introduction To Mobile Application Development: Week 9

The document discusses three primary ways to persist data in Android applications: 1. SharedPreferences for saving small chunks of user preference data in key-value pairs to an XML file. 2. Traditional file systems for saving larger amounts of data like text to internal storage files. 3. SQLite databases for storing structured data in tables using the SQLite interface.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

ITE 2152

Introduction to Mobile
Application Development
Week 9

M P C Sandaru – Software Engineer


How to persist data in android
• For android, there are primarily three ways of
presisting data:
– Lightweight mechanism known as shared
preferences to save small chaunks of data
– Traditional file systems
– A relational database management system
through the support of Sqlite databases
Saving & loading user preferences
• Android provides the SharedPreferences
object to help you save simple application
data.
– For example, your application may have an option
that enables users to specify the font size used in
your app.
– In this case your application needs to remember
the size set by the user so that the size is set
appropriately each time the app is opened.
Saving & loading user preferences
(cont...)
• You have several options for saving this type of
preferences
– Save data to a file : but you have to perform some file
management routines, such as writing the data to the file,
indicating how many characters to read from it. If you
have several information such as text size, font name, bg
color then this become hard.
– Writing text to a database – As a alternative write to a
database. But use a database to save some simple data in
an overtime task.
– Using the SharedPreferences object – This saves data
through the use of name/value pairs. For example, specify
a name for data you want to save, and then both it and its
value will be saved automatically to an XML file.
Example
• Create a project called “Using Preferences”
• Create a new subdirectory in the res directory
and name it xml. In this newly created
directory, add a file and name it
mypreferences.xml.
Example (cont…)
Example (cont…)
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Category 1">
<CheckBoxPreference
android:title="Checkbox"
android:defaultValue="false"
android:summary="True or False"
android:key="checkboxPref" />
</PreferenceCategory>
<PreferenceCategory android:title="Category 2">
<EditTextPreference
android:summary="Enter a string"
android:defaultValue="[Enter a string here]"
android:title="Edit Text"
android:key="editTextPref" />
<RingtonePreference
android:summary="Select a ringtone"
android:title="Ringtones"
android:key="ringtonePref" />
<PreferenceScreen
android:title="Second Preference Screen"
android:summary= "Click here to go to the second Preference Screen"
android:key="secondPrefScreenPref" >
<EditTextPreference
android:summary="Enter a string"
android:title="Edit Text (second Screen)"
android:key="secondEditTextPref" />
</PreferenceScreen>
</PreferenceCategory>
</PreferenceScreen>
Example (cont…)

• Create another XML file in the res/xml folder and name it prefheaders.xml
<?xml version="1.0" encoding="utf-8"?>
<preference-headers
xmlns:android="http://schemas.android.com/apk/res/android">
<header android:fragment= "com.<enter your package name >
.usingpreferences.AppPreferenceActivity$PrefFragment“
android:title="Preferences"
android:summary="Sample preferences" />
</preference-headers>

• Under the app/java/<package name>, add a new class file and name it
AppPreerencesActivity.java
Example (cont…)
• AppPreferenceActivity.java
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import java.util.List;
public class AppPreferenceActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.prefheaders, target);
}
@Override
protected boolean isValidFragment(String fragmentName) {
return true;
}
public static class PrefFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); PreferenceManager.setDefaultValues(getActivity(),
R.xml.myapppreferences, false);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.myapppreferences);
}
}
}
Example (cont…)
• In the AndroidManifest.xml file, add new entry for the AppPreferenceActivity class. Please be sure to replace instances of
com.<your package name> with the package name used in the project.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com. <your package name>.usingpreferences">
<application
android:allowBackup="true" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="com. <your package name>.usingpreferences.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com. <your package name>.usingpreferences.AppPreferenceActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="com. <your package name>.AppPreferenceActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
• Activity_main.xml
Example (cont…)
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.jfdimarzio.usingpreferences.MainActivity">
<Button
android:text="Load Preferences Screen"
android:layout_width="310dp"
android:layout_height="wrap_content"
android:id="@+id/btnPreferences"
app:layout_constraintLeft_toLeftOf="@+id/activity_main"
android:layout_marginStart="40dp"
app:layout_constraintTop_toTopOf="@+id/activity_main"
android:layout_marginTop="16dp"
app:layout_constraintRight_toRightOf="@+id/activity_main"
android:layout_marginEnd="16dp"
app:layout_constraintBottom_toBottomOf="@+id/activity_main"
android:layout_marginBottom="16dp"
app:layout_constraintVertical_bias="0.0“
android:onClick="onClickLoad"/>

<Button
android:text="Display Preferences Values"
android:layout_width="310dp"
android:layout_height="wrap_content"
android:id="@+id/btnDisplayValues"
app:layout_constraintLeft_toLeftOf="@+id/btnPreferences"
app:layout_constraintTop_toBottomOf="@+id/btnPreferences“
roid:layout_marginTop="16dp"
app:layout_constraintRight_toRightOf="@+id/btnPreferences"
android:onClick="onClickDisplay"/>
Example (cont…)
• Activity_main.xml
<EditText
android:layout_width="310dp"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editText" app:layout_constraintLeft_toLeftOf="@+id/btnPreferences"
app:layout_constraintTop_toBottomOf="@+id/btnDisplayValues" android:layout_marginTop="16dp"
app:layout_constraintRight_toRightOf="@+id/btnPreferences" />
<Button
android:text="Modify Preferences Values"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/btnModifyValues" app:layout_constraintLeft_toLeftOf="@+id/btnDisplayValues“
app:layout_constraintTop_toBottomOf="@+id/editText" android:layout_marginTop="16dp“
app:layout_constraintRight_toRightOf="@+id/btnDisplayValues" android:onClick="onClickModify" />
</android.support.constraint.ConstraintLayout>
Example (cont…)
• MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickLoad(View view) {
Intent i = new Intent("com.jfdimarzio.AppPreferenceActivity");
startActivity(i);
}
}
Example (cont…)
Persisting Data to Files
• Sometimes you might prefer to use the
traditional file system to store your data.
• For example, you might want to store the text
of poems you want to display in your
applications.
• In android, you can use the classes in the
java.io package to do so.
Persisting Data to Files (cont…)
• Saving Data to Internal Storage
– The first way to save files in your android applications
it to write to the device’s internal storage.
– To save text into a file, we use the FileOutputStream
class. The openFileOutput() method opens a named
file for writing, with the mode specified.
– We use the MODE_PRIVATE constant to indicate that
the file is readable by all other applications:
• FileOutputStream fOut = openFileOutput(“textfile.txt”,
MODE_PRIVATE);
Persisting Data to Files (cont…)
• To convert a character stream into a byte
stream, you use an instance of the
OutputStreamWriterclass, by passing it an
instance of the FileOutputStream object:
– putStreamWriter osw = new
OutputStreamWriter(fOut);
Persisting Data to Files (cont…)
• Saving to External Storage (SD Card)
– The previous section showed how you can save
your files in to the internal storage of your android
device.
– Because of its larger capacity, as well as the
capability to share the files easily with other users,
it would be useful to same data to external
storage.
Choosing the best storage option
• If we have data that can be represented using name/
value pairs, then use the SharedPreferences object. For
example, if you want to store user preference data
such as username, background color, date of birth or
last login date, then the SharedPreferences object is
the ideal way to store this data.
• If we need to store ad-hoc data then using the internal
storage is a good option. For example, our application
(such as RSS reader) might need to download images
from the web for display. In this scenario, saving the
images to internal storage is a good solution.
Creating and using databases
• For saving relational data, using a database is much
more efficient.
– For example, if you want to store the test results of all the
students in a school, it is much more efficient to use a
database to represent them because you can use database
querying to retrieve the results of specific students.
– Android uses the SQLite database system. The database
that you create for an application is only accessible to
itself; other applications will not be able to access it.
– For android, the SQLite database that you create
programmatically in an application is always stored in the
data/data/<package name>/database folder.
Creating the DBAdapter Helper class
• Let’s create a helper class called DBAdapter,
which creates, opens, closes, and uses a
SQLite database.
– In this example, you are going to create a
database named MyDB containing one table
named con-tacts. This table has three columns:
_id, name, and email.
• You first define several constants to contain the various
fields for the table that you are going to create in your
database:
• static final String KEY_ROWID = "_id";
• static final String KEY_NAME = "name";
• static final String KEY_EMAIL = "email";
• static final String TAG = "DBAdapter";
• static final String DATABASE_NAME = "MyDB";
• static final String DATABASE_TABLE = "contacts";
• static final int DATABASE_VERSION = 1;
• static final String DATABASE_CREATE = "create table
contacts (_id integer primary key autoincrement, " +
"name text not null, email text not null);";
• In particular, the DATABASE_CREATE constant contains
the SQL statement for creating the contactstable within
the MyDB database.
Summary
TOPIC KEY CONCEPTS
Saving simple user data Use the SharedPreferences object.
Sharing data among activities Use the getSharedPreferences() method.
in the same application
Saving to a file Use the FileOutputStream and OutputStreamReader
classes.
Reading from a file Use the FileInputStream and InputStreamReader
classes.
Saving to external storage Use the getExternalStorageDirectory() method to
return the path to the external storage.
Accessing files in the res/raw Use the openRawResource() method in the Resources
folder object (obtained via the getResources() method).
Creating a database helper Extend the SQLiteOpenHelper class.
class
Thank You!

You might also like