IT487 M6 Ch17 and Ch27 STD
IT487 M6 Ch17 and Ch27 STD
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);
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.
<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.
// 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();
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
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.
<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) {
// 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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dm = new DataManager(this);
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