0% found this document useful (0 votes)
26 views11 pages

M - Apps5 - Saving Persisting Data

The document discusses different methods for saving persistent data in Android mobile applications, including SQLite databases, shared preferences, internal memory, and external memory. It focuses on using SQLite databases, explaining how to create a database using SQLiteOpenHelper, perform queries and updates, and providing examples of database classes and methods.

Uploaded by

Ali Kareem
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)
26 views11 pages

M - Apps5 - Saving Persisting Data

The document discusses different methods for saving persistent data in Android mobile applications, including SQLite databases, shared preferences, internal memory, and external memory. It focuses on using SQLite databases, explaining how to create a database using SQLiteOpenHelper, perform queries and updates, and providing examples of database classes and methods.

Uploaded by

Ali Kareem
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/ 11

1/18/2021

IS457
Mobile Applications
Lecture 5
Saving Persisting Data

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

Saving Persistent Data


• Saving methods
1- SQLite Database
- Uses the device internal memory to store data in a SQLite database file.
- Embedded into every android device within android operating system.
- Programmer defines statements to create and update. Android does the rest.
2- Shared Preferences
- Uses general framework in Android.

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

1
1/18/2021

Saving Persistent Data


3- Internal Memory
- using Linux file system.
- Local to app.
- Destroyed on uninstall.
4- External Memory
- Device dependent like SD card or flash memory.
- Shared across applications.

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

SQL Languages

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

2
1/18/2021

SQLite Database
• Pros
• Very light weight database
• Quick to sort and retrieve large data sets
• Can easily be used to store customized data
• Can enforce relationships and integrity between data
• Cons
• Uses space limited internal device memory

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

SQLite Database
• When an application creates a database it is saved in:

• DATA/data/APP_NAME/databases/FILENAME

• Where

• DATA is the path returned by Environment.getDataDirectory()


• APP_NAME is application name
• FILENAME is the name given by your code

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

3
1/18/2021

SQLite Database/ Data Types


• Text = java String
• Integer = java Long
• Real = java Double
• NULL= the value is a NULL value
• BLOB = A Binary Large OBject is a collection of binary data stored as a single
entity in a database management system. Blobs are typically images, audio or
other multimedia objects, though sometimes binary executable code is stored
as a blob
• No other types available. All data must be converted to one of these

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

SQLite Database
• Imports
• android.database
contains all necessary classes
• android.database.sqlite
contains SQLite specific classes

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

4
1/18/2021

SQLite Database
• Subclass SQLiteOpenHelper to create and upgrade database.
• In the constructor you invoke superclass with your database name and current
version.
• Override onCreate() and onUpgrade().
• SQLiteOpenHelper provides programmer with:
- getReadableDatabase()
- getWriteableDatabase() methods.
• Use _id attribute as (autoincrement) primary key

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

SQLiteOpenHelper Example
Subclass SQLiteOpenHelper to create
and upgrade database

public class DBHelper extends SQLiteOpenHelper { Use _id attribute as


public static final String TABLE_CONTACTS= "contacts"; (autoincrement) primary key
public static final String COLUMN_ID= "_id";
public static final String COLUMN_NAMES= "names";

public static final String DATABASE_NAME= "contacts.db";


public static final int DATABASE_VERSION= 1;

private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_CONTACTS + "
(" + COLUMN_ID +
" integer primary key autoincrement," + COLUMN_NAMES + " TEXT NOT
NULL);";

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

5
1/18/2021

SQLiteOpenHelper
In the constructor you invoke superclass
with your database name and current
version

public DBHelper (Context context){


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database){
database.execSQL(TABLE_CREATE);
}
@Override
public void onUpgrade (SQLiteDatabase db, int oldversion, int newversion){
Log.w(DBHelper.class.getName(), "Upgrating data from version " + oldversion
+ "to " + newversion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
}

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

SQLite Database
• SQLiteDatabase provide
- Insert()
- Update()
- Delete()
- execSQL()

• Use ContentValues to insert or update table entries.


• ContentValues is key/value pair
• Key = Column identifier. Value is table entry

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

6
1/18/2021

SQLite Database / Queries


• Query provides structured interface for specifying sql query
• return database.query(DATABASE_TABLE, new String[] {COLUMN_ID
, COLUMN_NAMES}, null, null, null, null, null, null);
• String DATABASE_TABLE = The table name to query
• String[] column names = columns to return. Null = all columns
• String = where clause. Null selects all rows
• String[] selection args. Where clause can accept as place holders. These are
replaced by values in selection args
• String[] group by. A filter declaring how to group rows, null = not grouped.
• String[] having. Filter for groups. Null = no filter
• String[] Order by. Table names to order by. Null = no ordering

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

SQLite Database / Queries


• In /SQL
• SELECT col-1, col-2 FROM tableNameWHERE col-1=apple,col-2=mango
GROUPBY col-3 HAVING Count(col-4) > 5 ORDERBY col-2 DESC LIMIT
15
• In SQLite
• String table = "tableName"; String[] columns = {"col-1", "col-2"}; String
selection = "col-1 =? AND col-2=?"; String[] selectionArgs =
{"apple","mango"}; String groupBy =col-3; String having =" COUNT(col-
4) > 5"; String orderBy = "col-2 DESC"; String limit = "15";
• query(tableName, columns, selection, selectionArgs, groupBy, having,
orderBy, limit);

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

7
1/18/2021

SQLite Database / Queries


• All queries return a Cursor object.

• Provides:

- getCount()
- moveToFirst()
- moveToNext()

• Cursors must be closed after use

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

SQLiteDatabase Class example


public class SQLData {
public DBHelper dbHelper; public Context mycontext; public SQLiteDatabase
database;

public SQLData (Context c){


mycontext=c; }
public SQLData OpenBD() throws android.database.SQLException{
dbHelper = new DBHelper(mycontext);

database = dbHelper.getWritableDatabase();
return this;}

public void close(){


dbHelper.close();}

public void InsertDataBase(String name){

ContentValues contentValues= new ContentValues();


contentValues.put(DBHelper.COLUMN_NAMES, name);
database.insert(DBHelper.TABLE_CONTACTS, null, contentValues); }

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

8
1/18/2021

SQLiteDatabase Class example


public Cursor ReadData(){
String[] toDataBaseColumns = new String[]{DBHelper.COLUMN_ID,
DBHelper.COLUMN_NAMES};
Cursor cursor = database.query(DBHelper.TABLE_CONTACTS,
toDataBaseColumns, null, null, null, null, null, null);
if (cursor !=null){
cursor.moveToFirst();
}
return cursor;
}
public void delete(Long theID){
database.delete(DBHelper.TABLE_CONTACTS,DBHelper.COLUMN_ID + "=" + theID,
null);
}
}

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

Shared Preference
• General framework in Android that will allow you to save/retrieve key value pairs for
primitive objects such as boolean, float, int, long and string.
• Pros
• Really built-in to the existing Android framework, so easy to use, and easy to create a
preference activity to view and edit the preferences
• Quick
• Can really be used to store any data with manipulation with the string type.
• Cons
• Not suitable for storing very large amounts of data, as it will be slow in retrieving and
sorting through the data.
• Use internal device memory (more limited than external)
• Requires customization for any non-primitive data types.

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

9
1/18/2021

Writing Shared Preference


• The method getSharedPreferences() returns a SharedPreference instance
pointing to the file that contains the values of preferences

public static final String MY_PREFS = "My_Prefs_File”


SharedPreferences prefs = getSharedPreferences (MY_PREFS, MODE_PRIVATE);

• MODE_PRIVATE: the file can only be accessed using calling application


• MODE_APPEND: append the new preferences with the already existing
preferences

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

Writing Shared Preference


• Save in the sharedpreferences
SharedPreferences.Editor editor = prefs.edit();

editor.putString("name", “Sarah");
editor.putInt(“age", 12);
editor.commit();

• putFloat(String key, float value): save a integer value in a preference editor


• ……. etc.

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

10
1/18/2021

Writing Shared Preference


• Other methods available in the editor class
clear(): remove all values from the editor
remove(String key): It will remove the value whose key has been passed as a
parameter

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

Reading Shared Preference

• SharedPreferences prefs = getSharedPreferences (MY_PREFS,


MODE_PRIVATE);
Default value

• String name = prefs.getString(“name”, “No name”);


int age = prefs.getInt(“age”, 0);

• Example

COMPUTER INFORMATION SYSTEM DEPARTMENT ASS.LEC. ZAINAB H. ALFAYEZ

11

You might also like