0% found this document useful (0 votes)
12 views50 pages

IT487 M6 Ch17 and Ch27 STD

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views50 pages

IT487 M6 Ch17 and Ch27 STD

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

‫الجامعة السعودية االلكترونية‬

‫الجامعة السعودية االلكترونية‬

‫‪26/12/2021‬‬
College of Computing and
Informatics
Bachelor of Science in Computer
Science
IT487
Mobile Application Development
IT487
Mobile Application Development

Module 6
Data Persistence and Sharing & Android
Databases
Contents
1.Android intents
2.Persisting data with SharedPreferences
3.Reloading data with SharedPreferences
4.More advanced persistence
5.Databases 101& SQL syntax prime
6.Android SQLite API
7.Coding the database class
8.Coding the DataManager class
9.Running the “SQLiteDatabase” Database app
Weekly Learning
Outcomes
1. Explain about using Android intents to switch between
Activity classes and pass data.
2. Design the screen data using the SharedPreferences class &
JavaScript Object Notation.
3. Explain the Android SQLite.
Required Reading
1. Chapter 17 & Chapter 27 (Android Programming for
Beginners 3rd Edition, 2021 by John Horton , Packt
Publishing Ltd.)
Objectives of the chapter
• Different ways to store data in Android device’s permanent storage
• Adding a second Activity class to the app and navigating between the two screens
• Using Android intents to switch between Activity classes and pass data
• Create a simple (very simple) settings screen in a new Activity class
• Persist the settings screen data using the SharedPreferences class.
• Learn about JavaScript Object Notation (JSON) for serialization.
• Implement saving data.
Android Intents
Android intents
• Android apps comprises of multiple Activities.
• *Intent class: class that demonstrates the intent of an Activity class.
• Intent class: enables the user to switch between Activity instances.
• *Activity instances: made from classes with member variables.
• When switching between the multiple screens in an app, the Intents handle variable’s data
value by passing data between Activity instances.
• Intents also enables to interact with other apps too.
• For example, we could provide a link in our app for the user to send an email, make a
phone call, interact with social media, or open a web page in a browser and have the email
app, phone call app, social media app, or web browser do all the work.
Switching Activity
• Consider an app with two Activity based classes. One of the class is FirstActivity class which
will be the starting point of the app. Second activity is the SecondActivity.
• Switching between the two screens: given in the code.
// Declare and initialize a new Intent object called myIntent
Intent myIntent = new Intent(this, SecondActivity.class);
// Switch to the SecondActivity
startActivity(myIntent);
• In code above, we:
• Initializing the Intent object (myIntent).
• Intent has a constructor with two arguments/parameters:
1. The first parameter “this”: is a reference to current activity class (FirstActivity.class)
2. The second parameter is the name of the Activity class we want to open, SecondActivity.class
• *Encapsulation : Hides the information about each other activities  How to share the data?
Passing data between activities
• Intent uses to send/pass a data from one activity to second activity.
• Consider a sign-in screen: user need to pass the user's credentials to each Activity of app
 Done by using intents.
public class FirstActivity extends AppCompatActivity {
// Create a String called username and set its value to1.Bob
We create a String called username
String username = "Bob"; // 1 and set its value to Bob.
2. We used the putExtra method to load
@Override
protected void onCreate(Bundle savedInstanceState) { a string (data) into the intent.
super.onCreate(savedInstanceState); • We add data using key-value pairs.
setContentView(R.layout.activity_main); • Key: USER_NAME
• value: username
// Declare and initialize a new Intent object called myIntent
• *Each piece of data needs to be
Intent myIntent = new Intent(this, SecondActivity.class);
// Add the username String to the Intent using the accompanied by an identifier
// putExtra method of the Intent class instance that can be used in the
myIntent.putExtra("USER_NAME", username); // 2retrieving Activity to identify and
// Start the new Activity
retrieve the data.
startActivity(myIntent);
}
}
Passing data between activities
• In SecondActivity, we could then retrieve the string like this:
public class SecondActivity {
// In the receiving Activity, we create the get Intent object
Intent myIntent = getIntent();
// Initialize username with the passed in String
String username =
myIntent.getExtras().getString("USER_NAME");
}
• We can retrieve the data using the getExtras method and the appropriate
identifier from the key-value pair.
• key (USER_NAME) must be same which is send by first activity.
• getString() method is for getting the data (key) which is send by first activity.
• The Intent class can help when sending more complex data.
Passing data between activities (Example)
• Create an empty project. Name it Intent.
• Intent project has a class named FirstActivity and layout named activity_first.xml
Passing data between activities (Example)
• Open “activity_first.xml” file and add the following inside of it.
<EditText
android:id="@+id/send_text_id"
android:layout_width="411dp"
android:layout_height="43dp"
android:hint="Input"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.052" />

<Button
android:id="@+id/send_button_id"
android:layout_width="99dp"
android:layout_height="50dp"
android:text="send"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.139" />
Passing data between activities (Example)
• Open the FirstActivity activity file and add the following code inside of it.
public class FirstActivity extends AppCompatActivity {
// Define the variables
Button send_button;
EditText send_text;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
send_button = (Button)findViewById(R.id.send_button_id);
send_text = (EditText)findViewById(R.id.send_text_id);

// add the OnClickListener in sender button


send_button.setOnClickListener(new View.OnClickListener() {
@Override
Passing data between activities (Example)
• Continue code from previous slide.
public void onClick(View v)
{
// get the value which input by user in EditText and convert it to string
String str = send_text.getText().toString();

// Create the Intent object of this class Context() to SecondActivity class


Intent intent = new Intent(getApplicationContext(), SecondActivity.class);

// putExtra method put the value in key-value pair


intent.putExtra("message_key", str);
// start the Intent
startActivity(intent);
}
});
}
}
Passing data between activities (Example)
• Now, we have to create a SecondActivity activity file that to receive the data.
• Right click on app folder -> New -> Activity -> Empty Activity
• Keep the default settings, but make sure that Generate a Layout File option is checked.
• Name the layout as activity_second.
• In activity_second.xml, add the following xml code.
<TextView
android:id="@+id/received_value_id"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="Received data"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.005" />
Passing data between activities (Example)
• Open the SecondActivity activity file and add the following code inside of it.
public class SecondActivity extends AppCompatActivity {
TextView receiver_msg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
receiver_msg = (TextView)findViewById(R.id.received_value_id);
// In the receiving Activity, we create the get Intent object
Intent myIntent = getIntent();
// receive the value by getString() and getExtras() methods
// key "message_key" must be same which is send by first activity
String str = myIntent.getExtras().getString("message_key");
// display the string into textView
receiver_msg.setText(str);
}
}
Passing data between activities (run the app)
• Run the app. Then, input a data and then click “SEND”.
• The data in the first activity will be send to the second activity.
Persisting data with SharedPreferences
Persisting data with SharedPreferences
• Persist, means that if the user quits the app, then come back to it, their data is still available.
• Three ways to make data persist.
1. A lightweight mechanism known as shared preferences.
2. Traditional file systems.
3. SQLite database system
• SharedPreferences class is a class that provides access to data that can be accessed and
edited by all Activity classes of an app.
• A SharedPreferences object can be used to store primitive data (for example, integers, strings,
app settings, username, password) in a key/value pair.
• To use SharedPreferences, we need to create two objects:
// A SharedPreferences for reading data
SharedPreferences prefs ;

// A SharedPreferences.Editor for writing data


SharedPreferences.Editor editor;
Persisting data with SharedPreferences: getSharedPreferences
• As with all objects, we need to initialize them before we can use them.
• We can initialize the prefs object by using the getSharedPreferences method and passing in
a string that will be used to refer to all the data read and written using this object.
• Initialize prefs the using:

prefs = getSharedPreferences("PREFS_FILE_NAME",
MODE_PRIVATE);

• PREFS_FILE_NAME: is a string the represent the file name that stores the key/value pairs.
• MODE_PRIVATE: means that any class, in this app only can access the preferences file.
Persisting data with SharedPreferences: Editor
• We then use our newly initialized prefs object to initialize our editor object by calling the edit
method:
editor = prefs.edit();
• We then save the key/value pair using:
editor.putString(“username_key", username_value);
editor.commit();
• putString(“username_key", username_value) is a method uses to save the username and
its value.
• Username_key is a label that can be used to refer to the data.
• username_value is the actual data we want to save.
• commit() is a method initiates the saving process.
• If you want to save an integer or boolean data, you can use a respective method:
editor.putInt("age_key", age);
editor.putBoolean("isStudent_key", student);
Reloading data with SharedPreferences
• Let's see how we can reload our data the next time the app is run. The code below will reload
the value that the previous code saved.

String username = prefs.getString("username_key", "new user");


• In the previous code, we load the data from disk using the method appropriate for the data type.
• Username_key is the same label we used to save the data in the first place.
• new user is the default value. If there is no data stored with that label, it will then return the
default value.
SharedPreferences (example)
• Create an empty project. Name it SharedPreferences.
• Open “activity_main.xml” file and add the following XML code inside of it.
<EditText
android:id="@+id/edit_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:hint="Enter your Name"
android:padding="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />

<EditText
android:id="@+id/edit_age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/edit_name"
android:layout_marginStart="12dp"
android:layout_marginTop="8dp"
android:hint="Enter your Age"
android:inputType="number"
android:padding="10dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edit_name" />
SharedPreferences (example)
• Open the MainActivity activity file and add the following code inside of it.

public class MainActivity extends AppCompatActivity {


private EditText name, age;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.edit_name); // get a reference to name
widget in layout
age = findViewById(R.id.edit_age); // get a reference to age widget in
layout
}
SharedPreferences (example)
• Continue code from previous slide.
// Store the data in the SharedPreference in the onPause() method
// When the user closes the application, onPause() will be called and data will be
stored
@Override
protected void onPause() {
super.onPause();

// Creating a shared pref object with a file name "MySharedPref_file" in


private mode
SharedPreferences prefs = getSharedPreferences("MySharedPref_file",
MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();

// write all the data entered by the user in SharedPreference and initiates the
saving process
editor.putString("name_key", name.getText().toString());
SharedPreferences (example)
• Continue code from previous slide.
// Fetch the stored data in onResume() when the app opened again
@Override
protected void onResume() {
super.onResume();

// Fetching the stored data from the SharedPreference


SharedPreferences sh = getSharedPreferences("MySharedPref_file",
MODE_PRIVATE);

// If there is no data stored in name_key, return the default values ""


// If there is no data stored in age_key, return the default values 0
String s1 = sh.getString("name_key", "");
int a = sh.getInt("age_key", 0);

// Setting the fetched data in the EditTexts in the layout


name.setText(s1);
age.setText(String.valueOf(a));
}
SharedPreferences (example)
• Run the app and observe the following.
1. User enters the data inside of the text fields.
2. If the user closes the app completely, the app is completely destroyed.
3. If the user reopens the application, the data entered previously will be reloaded in the text fields
through the SharedPreferences.

4. Data
1. Enter reloaded
the data again

3. Reopen
the app
2. Close
the app
More advanced persistence
More advanced persistence : JSON
• As the app features advances with more data  required to save and load java
objects including internal data (strings, Booleans and anything else)
• SharedPreferences wasn't designed for save java objects.
• Serialization is uses to save data objects.
• In serialization, the data objects are converted into bits and bytes to store on
the disk.
• De-serialization
• In de-serialization, the store bits and bytes are converted back to data objects
when reloading the app.
• JSON stands for JavaScript Object Notation
• JSON class in Android hide the complexity Serialization process.
• JSON is uses to send data between web applications and servers.
• Widely used in Android.
Databases 101 & Android Databases (Chapter 27)
Database
• What is a database?
• A database is place of storage and a means to retrieve, store, and manipulate data.
• *Internal structure of database varies greatly based on the database.
• What is SQL?
• SQL stands for Structured Query Language.
• SQL is the programming language that is used to manipulate the data in the
database.
• What is SQLite?
• SQLite is Android version of SQL.
• SQLite is a fully functional database management system (DBMS).
• SQLite uses queries written in SQL. Database example
SQLite example code
• Keywords are similar to JAVA:
• INSERT: Allows us to add data to the database
• DELETE: Allows us to remove data from the database
• SELECT: Allows us to read data from the database
• WHERE: Allows us to specify parts of the database, matching specific
criteria, that we want to use INSERT, DELETE, or
SELECT on
• FROM: Used to specify a table or column name in a database
• SQL has types:
• integer: uses for storing whole numbers
• text: uses for storing a simple name or address
• real: uses for storing large floating-point numbers
Operations on database
• Creating a table

• Inserting data into the database


Operations on database
• Retrieving data from the database

• Updating the database structure

scor
e
Android SQLite API
• Two fundamental classes to access the database API in Android:
- SQLiteDatabase class is the class represents the actual database.
- SQLiteDatabase has methods to create, delete, execute SQL commands.
- execSQL method: adding data to the database.
- rawQuery method: getting data from the database.

- SQLiteOpenHelper class is the class responsibly to deal with/manage


database itself and enable to get access to a database and initialize an
instance of SQLiteDatabase
- SQLiteDatabase has to override two methods:
- onCreate method: called the first time a database is used.
- onUpgrade method: called when we upgrade/modify our database using ALERT.
Database cursors
• Besides the classes that give us access to the database and the methods that allow us to
execute our queries, there is the issue of exactly how the results we get back from our queries
are formatted.
• Android Studio has a Cursor class.
• All our database queries will return object of type Cursor class.
Cursor c = dbase.rawQuery(query, null);
• where dbase is object of type SQLiteDatabase and query is the query on
database.
• We can use the methods of the Cursor class to selectively access the data of database
returned from the queries, as here:
Log.i(c.getString(1), c.getString(2));
• The previous code would output to logcat the two values stored in the first two columns of
the result that the query returned.
• It is the Cursor object itself that determines which row of our returned data we are currently
reading.
Coding the database class
SQLiteDatabase app - activity_main.xml (example)
• Create an empty project. Name it SQLiteDatabase.
• Open “activity_main.xml” file and add the following xml code inside of it.
<EditText
android:id="@+id/editName"
android:layout_width="255dp"
android:layout_height="45dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:hint="Type a name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.102"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.023" />

<EditText
android:id="@+id/editAge"
android:layout_width="255dp"
android:layout_height="42dp"
android:layout_below="@+id/editName"
android:layout_alignStart="@+id/editName"
android:layout_alignLeft="@+id/editName"
android:hint="Type their age"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.102"
app:layout_constraintStart_toStartOf="parent"
SQLiteDatabase app - DataManager.java (example)
• Creating a new class and name it DataManager.java.
• Open “DataManager.java” class and add the following code inside of it.
public class DataManager {
// We create a variable to represents the actual database.
private SQLiteDatabase dbase;
// We create variables for id, name and age table's columns.
public static final String TABLE_COLUMN_ID = "_id";
public static final String TABLE_COLUMN_NAME = "name";
public static final String TABLE_COLUMN_AGE = "age";

// We create variables for: Database name, database version and table name.
private static final String DB_NAME = "my_db";
private static final int DB_VERSION = 1;
private static final String TABLE_N_AND_A = "names_and_age";
// We add the constructor that will create an instance of SQLiteOpenHelper.
// The constructor also initializes the db member, which is our SQLiteDatabase reference.
public DataManager(Context context) {

// Create an instance of our internal myDbHelper class


myDbHelper helper = new myDbHelper(context);
// We get a reference/create a variable to a SQLiteDatabase object,
// using SQLiteOpenHelper’s getWritableDatabase() method
// as we are writing data in our database.
dbase = helper.getWritableDatabase();
}
SQLiteDatabase app - DataManager.java (example)
• Continue code from previous slide.
// create a Database Helper class whose only function is to provide for
// the creation, modification, and deletion of tables in the database.
// The primary function of the class is to determine what must be done on
// creation of the database and what must be done when the database is upgraded.

// A Context is a handle to the system; it provides services like resolving resources,


// obtaining access to databases and preferences, and so on.
private class myDbHelper extends SQLiteOpenHelper {

public myDbHelper(Context context) {


super(context, DB_NAME, null, DB_VERSION);
}
// This method only runs the first time the database is created.
// The onCreate method is for creating a database by running a sqlite query
@Override
public void onCreate(SQLiteDatabase dbase) {
// Create a table for data and all their details
// On below line we are creating an sqlite query and we are
// setting our column names along with their data types.
String query = "create table " + TABLE_N_AND_A + " ("
+ TABLE_COLUMN_ID + " integer primary key autoincrement not null,"
+ TABLE_COLUMN_NAME + " text not null,"
+ TABLE_COLUMN_AGE + " text not null);";
// Here, we call execSQL method to execute above sql query
dbase.execSQL(query);
}
SQLiteDatabase app - DataManager.java (example)
• Continue code from previous slide.
@Override
public void onUpgrade(SQLiteDatabase dbase, int oldVersion, int newVersion) {
// The onUpgrade method is left intentionally blank for this app.
}
}

// Insert a record into the database table


// When adding/deleting data to the database, we will use execSQL, and
// when getting data from the database, we will use the rawQuery method
public void insert(String name, String age){
// Add all the details to the table
String query = "INSERT INTO " + TABLE_N_AND_A
+ " (" + TABLE_COLUMN_NAME + ", " + TABLE_COLUMN_AGE + ") "
+ "VALUES "
+ "(" + "'" + name + "'" + ", " + "'" + age + "'" + "); ";
Log.i("insert() = ", query);
dbase.execSQL(query);
}

// Delete a record from the database table


public void delete(String name){
// Delete the details from the table if already exists
String query = "DELETE FROM " + TABLE_N_AND_A +
" WHERE " + TABLE_COLUMN_NAME + " = '" + name + "';";
Log.i("delete() = ", query);
dbase.execSQL(query);
}
SQLiteDatabase app - DataManager.java (example)
• Continue code from previous slide.
// Get all the records from the database table
public Cursor selectAll() {
Cursor c = dbase.rawQuery("SELECT *" +" from " + TABLE_N_AND_A, null);
return c;
}

// Find a specific record


public Cursor searchName(String name) {
String query = "SELECT " + TABLE_COLUMN_ID + ", "
+ TABLE_COLUMN_NAME + ", "
+ TABLE_COLUMN_AGE +
" from " + TABLE_N_AND_A +
" WHERE " + TABLE_COLUMN_NAME + " = '" + name + "';";

Log.i("searchName() = ", query);


Cursor c = dbase.rawQuery(query, null);
return c;
}

// Output the cursor contents to the logcat


public void showData(Cursor c){
// moveToNext method move Cursor to the next row that is ready for reading:
while (c.moveToNext()){
Log.i(c.getString(1), c.getString(2));
}
}
}
SQLiteDatabase app - MainActivity.java (example)
• Open “MainActivity.java” class and add the following code inside of it.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

// Variable names (references) for all buttons and EditText in activity_main.xml layout
Button btnInsert;
Button btnDelete;
Button btnSelect;
Button btnSearch;
EditText editName;
EditText editAge;
EditText editDelete;
EditText editSearch;

// This is our DataManager instance


DataManager dm;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dm = new DataManager(this);

// get a reference to the UI items/widgets/elements


btnInsert = (Button) findViewById(R.id.btnInsert);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnSelect = (Button) findViewById(R.id.btnSelect);
btnSearch = (Button) findViewById(R.id.btnSearch);
SQLiteDatabase app - MainActivity.java (example)
• Continue code from previous slide.
EditText editName = (EditText) findViewById(R.id.editName);
EditText editAge = (EditText) findViewById(R.id.editAge);
EditText editDelete = (EditText) findViewById(R.id.editDelete);
EditText editSearch = (EditText) findViewById(R.id.editSearch);

// Register/link MainActivity Button items with a listener.


// When the button clicked, onClick method will be called.

btnSelect.setOnClickListener(this);
btnInsert.setOnClickListener(this);
btnDelete.setOnClickListener(this);
btnSearch.setOnClickListener(this);
}
SQLiteDatabase app - MainActivity.java (example)
• Continue code from previous slide.

@Override
public void onClick(View v){
switch (v.getId()){
case R.id.btnInsert:
dm.insert(editName.getText().toString(), editAge.getText().toString());
Toast.makeText(this,"Data Inserted", Toast.LENGTH_LONG).show();
break;

case R.id.btnDelete:
dm.delete(editDelete.getText().toString());
Toast.makeText(this,"Data Deleted",Toast.LENGTH_LONG).show();
break;

case R.id.btnSearch:
dm.showData(dm.searchName(editSearch.getText().toString()));
break;

case R.id.btnSelect:
dm.showData(dm.selectAll());
break;
}
}
}
Running the SQLite Database app
• Run the app and add the names and ages to the database using the Insert button.

• Verify the execution is successful of data added by clicking “SELECT *” button and checking the
logcat window.
Running the SQLite Database app
• Enter a name to delete and click the DELETE button. Analyse the
output by clicking “SELECT *” button and checking the logcat window.

• Enter a name to search for and click the SEARCH button. Analyse the
output by checking the logcat window.
Thank
You

You might also like