ITE 2152 Introduction To Mobile Application Development: Week 9
ITE 2152 Introduction To Mobile Application Development: Week 9
Introduction to Mobile
Application Development
Week 9
• 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!