Android Data Storagefinal

35
Android Data Storage Srilakshmi.N Mobile Application Developer Symbioun Software Pvt Ltd

Transcript of Android Data Storagefinal

Page 1: Android Data Storagefinal

Android Data Storage

Srilakshmi.N

Mobile Application Developer

Symbioun Software Pvt Ltd

Page 2: Android Data Storagefinal

Agenda

• Android Data Storage Introduction

• Shared Preferences

• Internal Storage

• External Storage

• SQLite Database

• Sample Examples

Page 3: Android Data Storagefinal

Introduction

• In order to maintain the essential information across Application-Executions or Life Time Of the Application .

• Android provides several options for you to save persistent application data using Android Data Storage .

Page 4: Android Data Storagefinal

Shared Preferences

•Store private primitive data in key-value pairs.

Shared Preferences

• Syntax: SharedPreferences sharedpreferences = getSharedPreferences(MyPreferences, Context.MODE_PRIVATE);

• Shared preferences Data is stored in XML file in the directory data/data/<package name>/shared-prefs/pref.xml

Page 5: Android Data Storagefinal

Shared Preferences

• MODE_PRIVATE: only your app can access the file

• MODE_MULTI_PROCESS: Multiple processes can modify the same shared prefernce file

MODE_PRIVATEMODE_WORLD

_READABLE

MODE_WORLD_WRITABLE

MODE_MULTI_PROCESS

Accessing Modes:

Page 6: Android Data Storagefinal

To get a SharedPreferences object for your application, use one of two methods:

• getSharedPreferences() - Use this if you need multiple

preferences files identified by name, which you

specify with the first parameter.

• getPreferences() - Use this if you need only one

preferences file for your Activity. Because this will be

the only preferences file for your Activity, you don't

supply a name.

Accessing Shared Preferences

Page 7: Android Data Storagefinal

Shared Preferences

To write values:

•Call edit() to get a sharedpreferences.Editor

•Add values with methods such as putBoolean() and putString()

•Commit the new values with commit()

Shared Preferences Example

Page 8: Android Data Storagefinal

Shared Preferences Example

• OutPut

Page 9: Android Data Storagefinal

public class ActivityA extends Activity{

EditText username, password;

@Override

protected void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstsanceState);

setContentview(R.layout.activity_mainA);

username=(EditText) findViewById(R.id.edt1);

password=(EditText) findViewById(R.id.edt2); }

public void save(View view) {

SharedPreferences sp=getSharedPreferences(“Preferencename” MODE_PRIVATE);

SharedPreferences.Editor editor = SharedPreferences.edit();

Editor.putString(“name” “username.getText().toString() ”);

Editor.putString(“password” “password.getText().toString()”) ; }

public void next(View view) {

Toast.makeText(this,"Next" ,Toast.LENGHT_LONG).show();

Intent intent= new Intent(this,ActivityB.class);

startActivity(intent); } }

Example:

Page 10: Android Data Storagefinal

public class ActivityB extends Activity{

TextView username, password;

@Override

protected void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstsanceState);

setContentview(R.layout.activity_mainB);

username=(TextView) findViewById(R.id.txt1);

password=(TextView) findViewById(R.id.txt2); }

public void load(View view) {

SharedPreferences sp=getSharedPreferences(“Preferencename” MODE_PRIVATE);

String name=Sharedpreferences.getString(“name” “Default ”);

String password=Sharedpreferences.getString(“password” “Default ”);

username.setText(name);

Password.setText(password);}

public void previous(View view) {

Toast.makeText(this,"Next" ,Toast.LENGHT_LONG).show();

Intent intent= new Intent(this,ActivityA.class);

startActivity(intent) } }

Page 11: Android Data Storagefinal

Using the Internal Storage

Internal Storage – Store Private data on device memory.

To create and write a private file to the

internal storage:

1. Call openOutput() with the name of the file

and operating mode. It Returns

FileOutPutStream.

2. Write to the file with write()

3. Close the stream with close()

Page 12: Android Data Storagefinal

Example:

String FILENAME = "hello_file";

String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);

fos.write(string.getBytes());

fos.close();

Note:To store static file save the file in your project res/raw/ directory. Open it with openRawResource(), passing the R.raw.<filename> resource ID. This method returns an InputStream that you can use to read the file (but you cannot write to the original file).

Page 13: Android Data Storagefinal

Internal Storage

To read a file from internal storage:

•Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.

•Read bytes from the file with read().

•Then close the stream with close().

Page 14: Android Data Storagefinal

Saving cache files

• If you'd like to cache some data, rather than store it persistently, you should use getCacheDir() to open a File that represents the internal directory where your application should save temporary cache files.

•Cache files are the temperary files.

Page 15: Android Data Storagefinal

Other useful methods

• getFilesDir()

Gets the absolute path to the filesystem directory where your internal files are saved.

• getDir()

Creates (or opens an existing) directory within your internal storage space.

• deleteFile()

Deletes a file saved on the internal storage.

• fileList()

Returns an array of files currently saved by your application.

Page 16: Android Data Storagefinal

External Storage(SD Card)

Externnal Storage - Store public data on the shared

external storage.

Getting access to external storageIn order to read or write files on the external storage, your app must acquire the READ_EXTERNAL_STORAGE orWRITE_EXTERNAL_STORAGE system permissions.

For example:

<manifest ...><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

...</manifest>

Page 17: Android Data Storagefinal

/* Checks if external storage is available for read and write */

public boolean isExternalStorageWritable() {

String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {

return true;

}

return false;

}

/* Checks if external storage is available to at least read */

public boolean isExternalStorageReadable() {

String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state) ||

Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {

return true;

}

return false;

}

Example

Page 18: Android Data Storagefinal

SD Card

Checking Media Availability:

You should always call getExternalStorageState() to check whether the media is available or not.

Syntax: /* Checks if external storage is available for read and write */

public boolean isExternalStorageWritable() {

String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {

return true;

}

return false;

}

Page 19: Android Data Storagefinal

Saving files that can be shared with other apps• For example, here's a method that creates a directory for a

new photo album in the public pictures directory:

Example:

public File getAlbumStorageDir(String albumName) {

// Get the directory for the user's public pictures directory.

File file = new File(Environment.getExternalStoragePublicDirectory(

Environment.DIRECTORY_PICTURES), albumName);

if (!file.mkdirs()) {

Log.e(LOG_TAG, "Directory not created");

}

return file;

}

Page 20: Android Data Storagefinal

SQLite Database

SQLite Database - Store structured data in a private database.

• programmatically created SQLite database of an app is always stored in /data/data/<package>/databases folder with ( .db extension).

Page 21: Android Data Storagefinal

Saving files that can be shared with other apps

• To get a File representing the appropriate public directory, call getExternalStoragePublicDirectory(), passing it the type of directory you want, such as DIRECTORY_MUSIC, DIRECTORY_PICTURES, DIRECTORY_RINGTONES, or others.

• Syntax: File file = new File(Environment.getExternalStoragePublicDirectory(

Environment.DIRECTORY_PICTURES), albumName);

Page 22: Android Data Storagefinal
Page 23: Android Data Storagefinal
Page 24: Android Data Storagefinal

SQLite Database Process Architecture

Page 25: Android Data Storagefinal

SQLite Database

•Creating SQL object

Step:1 Importing package “android.database.sqlite.SQLiteDatabase”.

Step:2 Creating object

SQLiteDatabase object name=null;

Page 26: Android Data Storagefinal

SQLite Database

Creating Database Name

mydb=openOrCreateDatabase("DatabaseName5",

MODE_PRIVATE,null);

// mydb is sqlite object name .

// DatabaseName5 is nothing but database name

// MODE_PRIVATE is permissions of a table accessing

Page 27: Android Data Storagefinal

SQLite DatabaseDDL Statements – These statements are used to perfrom operations on schemas.They are

• Create• Alter• Drop

DML Statements – these statements are used to perform operations on the data present in schemas.Theyare

• Select• Insert• Delete

Creating Table Create:

mydb.execSQL("CREATE TABLE IF NOT EXISTS “ +TableName+" (ColumnName DataType);");Alter:

ALTER TABLE TableName RENAME TO new-table-nameDrop: DROP TABLE TableName

Page 28: Android Data Storagefinal

SQLite Database

• DDL Statements and syntax:

Create:Creates Schema with name

mydb.execSQL("CREATE TABLE IF NOT EXISTS “ +TableName+" (ColumnName DataType);");

Alter: Alters the name of the schema

ALTER TABLE TableName RENAME TO new-table-name

Drop: Drops the schema

DROP TABLE TableName

Page 29: Android Data Storagefinal

SQLite Database•DDL Statements and Syntax:

Select: To select particular data in schema

Cursor c=mydb.rawQuery("SELECT * FROM "+TableName+" where Name='"+city+"'",null);

Insert: To insert some data into schema

mydb.execSQL("INSERT INTO "+TableName+“ (Name, Area)“ + "VALUES ('RedFort','40.8 acres‘);");

Delete:To delete data

mydb.execSQL(“Delete"+TableName);

Note:The Cursor is always the mechanism with which you can navigate results from a database query and read rows and columns.

Page 30: Android Data Storagefinal

SQLite Database

• SQLite OpenHelper is a class to manage database creation and version management.

• This class take care of opening the database if it exists, creating it if it does not, and upgrading it as necessary.

• This is for creating db “onCreate(SQLiteDataBase)”.

• when the database needs to be upgraded

“onUpgrade (SQLiteDataBase db, int oldVersion, intnewVersion)”.

• when the database has been opened “onOpen (SQLiteDataBase db)”.

Page 31: Android Data Storagefinal

SQLite Database

Public class Activity extends SQLiteOpenHelper{

private static final String KEY_ID = "id";

private static final String KEY_NAME = "name";

public void onCreate(SQLiteDatabase mydb) {

mydb.execSQL("CREATE TABLE IF NOT EXISTS “ +TableName+" (ColumnName DataType);");

}

public void onUpgrade(SQLiteDatabase mydb, int oldVersion, intnewVersion) {

// Drop older table if existed

mydb.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

// Create tables again

onCreate(mydb);

} }

Page 32: Android Data Storagefinal

Data Storage

• Shared Preferences summary

1.Shared Preferences stores data as key-pairs only.

2.Key is required to read data from it.

3. Reading and storing data in it is very simple.

4. It is difficult to store and read large structured data

5. It saves primitives data type like string, int ,booleans, floats ,long etc

6. It is best to use Shared Preferences when only small amount of data needs to be stored eg few app settings, user login /password etc.

Page 33: Android Data Storagefinal

Data Storage

• SQLite Summary

1.It stores structured data as a database.

2.The data can be queried.

3.Reading data from sqlite database is slower and more expensive then shared preferences

4. It can save large data upto 200kb

5.SQLite database is useful for just about anything and very flexible.

6.It is best to use Sqlite when the data to be stored is large , structured and required searching .eg storing complete user details , storing data fetched by http request etc.

Page 34: Android Data Storagefinal

Android Data Storage

• Conclusion : Both Preferences and SQLite are having their importance based on the size of the data requirement in android.

Page 35: Android Data Storagefinal

ANY QUERIES???