0% found this document useful (0 votes)
161 views

Unit V

The document provides an overview of different data storage options for mobile applications, including shared preferences, internal storage, external storage, and SQLite databases. It discusses storing data persistently and introduces key classes and methods for each storage type. For shared preferences, it covers saving and retrieving data using the SharedPreferences class and editor. For internal storage, it discusses private storage on the device memory and using FileInputStream, FileOutputStream, and openFile methods. For external storage, it addresses storing data on the SD card and determining storage availability.

Uploaded by

Manchala Lalitha
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)
161 views

Unit V

The document provides an overview of different data storage options for mobile applications, including shared preferences, internal storage, external storage, and SQLite databases. It discusses storing data persistently and introduces key classes and methods for each storage type. For shared preferences, it covers saving and retrieving data using the SharedPreferences class and editor. For internal storage, it discusses private storage on the device memory and using FileInputStream, FileOutputStream, and openFile methods. For external storage, it addresses storing data on the SD card and determining storage availability.

Uploaded by

Manchala Lalitha
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/ 18

MOBILE APPLICATION DEVELOPMENT

UNIT V

Unit V contents at a glance:

1. Storing the data persistently-Introducing the Data Storage Options:


 The preferences,
 The Internal Storage,
 The External Storage,
 The Content Provider
2. The SQLite database(CRUD operations-Insert,delete,update,select),
3. Connecting with the SQLite database
4. operations-Insert, Delete, Update, Fetch,
5. Publishing android applications-preparing for publishing,
6. Deploying APK files

1. Storing the data persistently-Introducing the Data Storage Options:


Android provides many ways of storing data of an application. They are as given below:
1. The Shared preferences,
2. The Internal Storage,
3. The External Storage,
4. The Content Provider

1. The Shared preferences:


Android shared preference is used to store and retrieve primitive information. In android, string, integer, long, number
etc. are considered as primitive data type. Shared Preferences allow you to save and retrieve data in the form of key,
value pair.
In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference
instance pointing to the file that contains the values of preferences.

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

The first parameter is the key and the second parameter is the MODE
MODE_PRIVATE

By setting this mode, the file can only be accessed using calling application
MODE_WORLD_READABLE

This mode allow other application to read the preferences


MODE_WORLD_WRITEABLE

This mode allow other application to write the preferences

**SharedPreferences can be implemented by using either Preferences Activity class file or using EDITOR
class(getsharedPreferences())

1
SAVING DATA IN SHARED PREFERENCES:
1. We can save something in the sharedPreferences by using SharedPreferences.Editor class.
2. call edit() of SharedPreference instance and will receive it in an editor object.

Editor editor = sharedpreferences.edit();


editor.putString("key", "value");
editor.commit();

important methods:
[I] putInt(): to save primitive type data
[II] commit(): To save the values kept in primitive functions
[III] getInt(): To get saved Integer value
[IV] remove(String key): To remove any key based data from preference file
[V] clear(): To clear all data

sample code for Saving and Retrieving Data in SharedPreference:

public static final String PREFS_GAME ="com.androidv.GamePlay";


public static final String GAME_SCORE= "GameScore";

//======== Code to save data ===================

SharedPreferences sp = getSharedPreferences(PREFS_GAME ,Context.MODE_PRIVATE);


sp.edit().putInt(GAME_SCORE,100).commit();

//========= Code to get saved/ retrieve data ==============

SharedPreferences sp = getSharedPreferences(PREFS_GAME ,Context.MODE_PRIVATE);


int sc = sp.getInt(GAME_SCORE,0);
Log.d("sachin","achieved score is "+ sc);

2
2. Internal Storage:

For reading or writing data, the following classes and methods are used:
1. FileInputStream[provides methods for reading files-read() etc]
2. FileOutputStream[provides methods for writing files-write() etc]
3. openFileInput(file)[ used to open a file and read it]
4.openFileOutput(file)[ used to create and save a file]

 Android Internal storage is the storage of the private data on the device memory. The stored data in memory is
allowed to read and write files.
 When files are stored in internal storage these file can only be accessed by the application itself not by other
applications.
 These files in storage exist till the application stays over the device, as you uninstall associated files get removed
automatically.
 The files are stored in directory data/data which is followed by the application package name.
 User can explicitly grant the permission to other apps to access files.
 To make the data private i.e you can use MODE_PRIVATE as discussed below about the modes.
 Technique is best suited when data can only be access by the application neither by the user nor by other apps.
 The data is stored in a file which contains data in bit format so it’s required to convert data before adding it to a
file or before extracting from a file.

Modes of Internal Storage:

MODE_PRIVATE — In private mode the data stored earlier is always overridden by the current data i.e every time you
try to commit a new write to a file which removes or override the previous content.
MODE_APPEND — In this mode the data is append to the existing content i.e keep adding data.

openFileOutput(): This method is used to create and save a file. Its syntax is given below:

FileOutputStream fOut = openFileOutput("file name",Context.MODE_PRIVATE);

The method openFileOutput() returns an instance of FileOutputStream.


openFileInput(): This method is used to open a file and read it. It returns an instance of FileInputStream. Its syntax is
given below:
FileInputStream fin = openFileInput(file);

Write data to file in Internal Storage(write()):

 Define the filename as string and also define data you wanna write to file as string or in any format generated
from app or any other source.
 Use FileOutputStream method by creating its object as defined.
 Convert data into byte stream before writing over file because file accepts only byte format further close the file
3
using file object.

String File_Name= "Demo.txt"; //gives file name


String Data="Hello!!"; //define data

FileOutputStream fileobj = openFileOutput( File_Name, Context.MODE_PRIVATE);


byte[] ByteArray = Data.getBytes(); //Converts into bytes stream
fileobj.write(ByteArray); //writing to file
fileobj.close(); //File closed

Reading file(read())

In order to read from the file you just created , call the openFileInput() method with the name of the file. It returns an
instance of FileInputStream. Its syntax is given below −

FileInputStream fin = openFileInput(file);

you can call read method to read one character at a time from the file and then you can print it. Its syntax is given below

int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}

//string temp contains all the data of the file.


fin.close();

4
3. External Storage:

The data is stored in a file specified by the user itself and user can access these file. These files are only accessible till
the application exits or you have SD card mounted on your device.

we can use the following classes and methods for reading or writing data using SD card:
1. FileInputStream[provides methods for reading files-read() etc]
2. FileOutputStream[provides methods for writing files-write() etc]
3. isExternalStorageAvailable()
4.isExternalStorageReadOnly()
5. getExternalStorageState() is a static method of Environment to determine if external storage is presently available
or not.
Note: It is necessary to add external storage the permission to read and write. For that you need to add permission in
android Manifest file.
Open AndroidManifest.xml file and add permissions to it just after the package name.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

External storage such as SD card can also store application data, there’s no security enforced upon files you save to the
external storage.
In general there are two types of External Storage:

 Primary External Storage: In built shared storage which is “accessible by the user by plugging in a USB cable and
mounting it as a drive on a host computer”. Example: When we say Nexus 5 32 GB.
 Secondary External Storage: Removable storage. Example: SD Card
getExternalStorageState() is a static method of Environment to determine if external storage is presently available or
not.

Methods to Store Data In Android:

 getExternalStorageDirectory() – Older way to access external storage in API Level less than 7. It is absolute now
and not recommended. It directly get the reference to the root directory of your external storage or SD Card.
 getExternalFilesDir(String type) – It is recommended way to enable us to create private files specific to app and
files are removed as app is uninstalled. Example is app private data.

5
 getExternalStoragePublicDirectory() : This is current recommended way that enable us to keep files public and
are not deleted with the app uninstallation.
sample code to check external storage available or not:

if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
saveButton.setEnabled(false);
}

private static boolean isExternalStorageReadOnly() {


String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}

private static boolean isExternalStorageAvailable() {


String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}

6
4. Content Providers:
A content provider component supplies data from one application to others on request. Such requests are handled by
the methods of the ContentResolver class.
It is a component which
i)- hides database details (database name, table name, column info. etc.)
ii)- allows the application to share data among multiple applications.

Content providers let you centralize content in one place and have many different applications access it as needed.
data is stored in an SQlite database
A content provider is implemented as a subclass of ContentProvider class

public class My Application extends ContentProvider


{
}

list of methods which you need to override in Content Provider class:

 onCreate() This method is called when the provider is started.


 query() This method receives a request from a client. The result is returned as a Cursor object.
 insert()This method inserts a new record into the content provider.
 delete() This method deletes an existing record from the content provider.
 update() This method updates an existing record from the content provider.
 getType() This method returns the MIME type of the data at the given URI.

7
7
 Steps to create Content Provider:

i)- Create ContentProvider subclass (android.ContentProvider).


ii)- Register ContentProvider in AndroidManifest.xml file using provider element. (<provider>).
To Register ContentProvider use following attributes:
i)- android:name -> ContentProvider subclass name.
ii)- android:authorities -> authority used for ContentProvider
iii)- android:exported -> true/false.
true: ContentProvider can be used in other applications.
false: ContentProvider can be used in local application.
By default, it is “true”.

Content URIs

To query a content provider, you specify the query string in the form of a URI which has following format −

<prefix>://<authority>/<data_type>/<id>

SQLite Database:

SQLite is a opensource SQL database that stores data to a text file on a device.
SQLite is an open-source relational database i.e. used to perform database operations on android devices such as
storing, manipulating or retrieving persistent data from the database.

SQLiteDatabase class

It contains methods to be performed on sqlite database such as create, update, delete, select etc.

Methods of SQLiteDatabase class

Method Description
void execSQL(String sql) executes the sql query not select query.
inserts a record on the database. The table specifies the table name,
long insert(String table, String nullColumnHack doesn't allow completely null values. If second argument
nullColumnHack, ContentValues values) is null, android will store null values if values are empty. The third
argument specifies the values to be stored.
int update(String table, ContentValues
values, String whereClause, String[] updates a row.
whereArgs)
Cursor query(String table, String[] columns,
String selection, String[] selectionArgs,
returns a cursor over the resultset.
String groupBy, String having, String
orderBy)

8
Database - Package

The main package is android.database.sqlite that contains the classes to manage your own databases

Database - Creation

In Android, the SQLiteDatabase namespace defines the functionality to connect and manage a database. It provides
functionality to create, delete, manage and display database content.
Create a Database or connecting to SQLite database:
Simple steps to create a database and handle are as following.

1. Create "SQLiteDatabase" object.


2. Open or Create database and create connection.
3. Perform insert, update or delete operation.
4. Create Cursor to display data from table of database.
5. Close the database connectivity.
Following tutorial helps you to create database and insert records in it.

Step 1: Instantiate "SQLiteDatabase" object

SQLiteDatabase db;

Before you can use the above object, you must import the android.database.sqlite.SQLiteDatabase namespace in your
application.

db=openOrCreateDatabase(String path, int mode, SQLiteDatabase.CursorFactory factory)

This method is used to create/open database. As the name suggests, it will open a database connection if it is
already there, otherwise it will create a new one.

Example,

db=openOrCreateDatabase("XYZ_Database",SQLiteDatabase.CREATE_IF_NECESSARY,null);

Step 2:Database table creation:

db.execSQL("CREATE TABLE IF NOT EXISTS student(Username VARCHAR,Password VARCHAR);");

Step 3:Database - Insertion

we can create table or insert data into table using execSQL method defined in SQLiteDatabase class. Its syntax is given
below

db.execSQL("CREATE TABLE IF NOT EXISTS student(Username VARCHAR,Password VARCHAR);");


db.execSQL("INSERT INTO student VALUES('admin','admin');");

execSQL(String sql, Object[] bindArgs)


This method not only insert data , but also used to update or modify already existing data in database using bind
arguments
Step 4:Database - Fetching (creation of cursor)

We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called
9
rawQuery and it will return a resultset with the cursor pointing to the table.

Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);


resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);

Database - Helper class

For managing all the operations related to the database , an helper class has been given and is called SQLiteOpenHelper.

public class DBHelper extends SQLiteOpenHelper {


public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}

Program for implementing database operations using SQLiteDatabase class:

activity_main.xml

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="50dp"
android:layout_y="20dp"
android:text="Student Details"
android:textSize="30sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="110dp"
android:text="Enter Rollno:"
android:textSize="20sp" />

<EditText
android:id="@+id/Rollno"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="100dp"
android:inputType="number"
android:textSize="20sp" />

<TextView
10
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="160dp"
android:text="Enter Name:"
android:textSize="20sp" />

<EditText
android:id="@+id/Name"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="150dp"
android:inputType="text"
android:textSize="20sp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="210dp"
android:text="Enter Marks:"
android:textSize="20sp" />

<EditText
android:id="@+id/Marks"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="200dp"
android:inputType="number"
android:textSize="20sp" />

<Button
android:id="@+id/Insert"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="25dp"
android:layout_y="300dp"
android:text="Insert"
android:textSize="30dp" />

<Button
android:id="@+id/Delete"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="200dp"
android:layout_y="300dp"
android:text="Delete"
android:textSize="30dp" />

<Button
android:id="@+id/Update"
android:layout_width="150dp"
11
android:layout_height="wrap_content"
android:layout_x="25dp"
android:layout_y="400dp"
android:text="Update"
android:textSize="30dp" />

<Button
android:id="@+id/View"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="200dp"
android:layout_y="400dp"
android:text="View"
android:textSize="30dp" />

<Button
android:id="@+id/ViewAll"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_x="100dp"
android:layout_y="500dp"
android:text="View All"
android:textSize="30dp" />

</AbsoluteLayout>

MainActivity.java

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity implements android.view.View.OnClickListener {

EditText Rollno,Name,Marks;
Button Insert,Delete,Update,View,ViewAll;
SQLiteDatabase db;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
12
Rollno=(EditText)findViewById(R.id.Rollno);
Name=(EditText)findViewById(R.id.Name);
Marks=(EditText)findViewById(R.id.Marks);
Insert=(Button)findViewById(R.id.Insert);
Delete=(Button)findViewById(R.id.Delete);
Update=(Button)findViewById(R.id.Update);
View=(Button)findViewById(R.id.View);
ViewAll=(Button)findViewById(R.id.ViewAll);

Insert.setOnClickListener(this);
Delete.setOnClickListener(this);
Update.setOnClickListener(this);
View.setOnClickListener(this);
ViewAll.setOnClickListener(this);

// Creating database and table


db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name VARCHAR,marks VARCHAR);");
}
public void onClick(View view)
{
// Inserting a record to the Student table
if(view==Insert)
{
db.execSQL("INSERT INTO student VALUES('"+Rollno.getText()+"','"+Name.getText()+
"','"+Marks.getText()+"');");

}
// Deleting a record from the Student table
if(view==Delete)
{

Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+Rollno.getText()+"'", null);


if(c.moveToFirst())
{
db.execSQL("DELETE FROM student WHERE rollno='"+Rollno.getText()+"'");
}

}
// Updating a record in the Student table
if(view==Update)
{
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+Rollno.getText()+"'", null);
if(c.moveToFirst())
{
db.execSQL("UPDATE student SET name='" + Name.getText() + "',marks='" + Marks.getText() +
"' WHERE rollno='"+Rollno.getText()+"'");
}
}
// Display a record from the Student table
if(view==View)
{

13
Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+Rollno.getText()+"'", null);
if(c.moveToFirst())
{
Name.setText(c.getString(1));
Marks.setText(c.getString(2));
}
}
// Displaying all the records
if(view==ViewAll)
{
Cursor c=db.rawQuery("SELECT * FROM student", null);
if(c.getCount()==0)
{

return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Rollno: "+c.getString(0)+"\n");
buffer.append("Name: "+c.getString(1)+"\n");
buffer.append("Marks: "+c.getString(2)+"\n\n");
}

}
}

14
Publishing android applications-preparing for publishing :

Generate signed APK and do Google play registration,do the following steps:
1. Create an account
2. Familiarize yourself with Developer Console
3. Fill in the necessary account details
4. Link your merchant account
5. Upload your app
6. Alpha and beta testing of app
7. Provide details for store listing
8. Add pricing and distribution details
9. Publishing the application
10. Device Filtering option

Deploying APK files:

Once you have signed your APK files, you need a way to get them onto your users’ devices. The following sections
describe the various ways to deploy your APK files. Three methods are covered:

 Deploying manually using the adb.exe tool


 Hosting the application on a web server
 Publishing through the Android Market

Besides these methods, you can install your applications on users’ devices through e-mails, SD card, and so on. As long
as you can transfer the APK file onto the user’s device, you can install the application.

15
SharedPreferences Sample program:

Java File:
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


EditText ed1,ed2,ed3;
Button b1;

public static final String MyPREFERENCES = "MyPrefs" ;


public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";

SharedPreferences sharedpreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);

b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();

SharedPreferences.Editor editor = sharedpreferences.edit();

editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
}

16
XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shared Preference "
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="35dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/textView2"
android:layout_marginTop="67dp"
android:hint="Name"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Pass" />

<EditText

17
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText3"
android:layout_below="@+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Email" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button"
android:layout_below="@+id/editText3"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp" />

</RelativeLayout>

output:

Now when you press save button, the text will be saved in the shared preferences. Now press back button and exit the
application.

18

You might also like