Unit V
Unit V
UNIT V
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
**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.
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
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.
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:
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.
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 −
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);
}
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.
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);
}
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
7
7
Steps to create Content Provider:
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.
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.
SQLiteDatabase db;
Before you can use the above object, you must import the android.database.sqlite.SQLiteDatabase namespace in your
application.
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);
we can create table or insert data into table using execSQL method defined in SQLiteDatabase class. Its syntax is given
below
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.
For managing all the operations related to the database , an helper class has been given and is called SQLiteOpenHelper.
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;
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);
}
// Deleting a record from the Student table
if(view==Delete)
{
}
// 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
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:
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;
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();
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