0% found this document useful (0 votes)
30 views36 pages

Android Unit - 4

The document discusses various data storage options in Android, including shared preferences, internal storage, and external storage. It explains how to use these storage methods for managing data securely and effectively, with examples of code for implementing shared preferences and file storage. Additionally, it highlights the importance of choosing the appropriate storage type based on data sensitivity and accessibility needs.
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)
30 views36 pages

Android Unit - 4

The document discusses various data storage options in Android, including shared preferences, internal storage, and external storage. It explains how to use these storage methods for managing data securely and effectively, with examples of code for implementing shared preferences and file storage. Additionally, it highlights the importance of choosing the appropriate storage type based on data sensitivity and accessibility needs.
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/ 36

Unit – 4

Data Storage
Data Storage is essential for maintaining knowledge, simplifying accessibility and
organisation, supporting decision-making procedures, assuring data security, encouraging
collaboration, and fulfilling legal responsibilities. For people, companies, and organisations
to manage and utilise their information assets effectively, proper data storage practices are
crucial.We use some kind of storage in Android to keep the data around indefinitely (until it's
deleted) for future use. These storage systems are referred to as Android Storage Systems.
Android provides a variety of storage choices, including internal storage, external
storage, shared preferences, databases, and shared storage. However, a lot of people are
confused about which storage to use and when. Understanding this is very important and
we'll explore it in detail in this article.
Data storage options are the following:
●​ Shared Preferences: Store private primitive data in key-value pairs.
●​ Internal Storage: Store private data on the device memory.
●​ External Storage: Store public data on the shared external storage.
●​ SQLite Databases: Store structured data in a private database.
●​ Contain Provider: Store structured or semi-structured data with user configurable
data access.
●​ File Storage: Store raw files on the phone memory or SD card
●​ Network Connection: Store data on the web with your own network server.

Share Preference
In android shared preference only allows to save primitive data type string, integer, long,
number etc. are considered as primitive data type.
Android Shared preferences are used to store data in key and value pair so that we can
retrieve the value on the basis of key.

To get access to the preferences, we have three APIs to choose from:


●​ getPreferences() : used from within your Activity, to access activity-specific
preferences(only one preference file call)Ex: getPreferences(int mode)
●​ getSharedPreferences() : used from within your Activity (or other application
Context), to access application-level preferences (several files
call)Ex:getSharedPreferences(String name, int mode)
Syntax:
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);​

Method:
o​ MODE_PRIVATE: the default mode, where the created file can only be accessed by
the calling application (only your app can access the file)
o​ MODE_WORLD_READABLE: Creating world-readable files is very dangerous, and
likely to cause security holes in applications (all apps can read the file)
o​ MODE_WORLD_WRITEABLE: Creating world-writable files is very dangerous, and
likely to cause security holes in applications(all apps can write the file)
o​ MODE_MULTI_PROCESS: This method will check for modification of preferences even
if the Shared Preference instance has already been loaded(Multiple processes can
modify the same shared preference file)
o​ MODE_APPEND: This will append the new preferences with the already existing
preferences
o​ MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag. When it is set, it
would enable write ahead logging by default.

How to use shared preference


●​ To store data
­​ Get a reference to the shared prefaces object (for single file call or several file
call)
­​ Call the editor
­​ Use the editor to add the data with key
­​ Commit editor changes
●​ To retrieve data
­​ Get a reference to the shared prefaces object (for single file call or several file
call)
­​ Use the key provided earlier to get data.
­​ Supply default values if the data is not found

Syntax:
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();
Example:
packagecom.example.myapplication;
importandroid.content.Context;
importandroid.content.SharedPreferences;
importandroid.os.Bundle;
import android.support.v7.app.AppCompatActivity;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.Toast;
publicclassMainActivityextendsAppCompatActivity{
EditText ed1,ed2,ed3;
Button b1;
publicstaticfinalStringMyPREFERENCES="MyPrefs";
publicstaticfinalStringName="nameKey";
publicstaticfinalStringPhone="phoneKey";
publicstaticfinalStringEmail="emailKey";
SharedPreferencessharedpreferences;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
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(newView.OnClickListener(){
@Override
publicvoidonClick(View v){
Stringn= ed1.getText().toString();
Stringph= ed2.getText().toString();
Stringe= 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();
}
});
}
}
Internal storage
These directories include both a dedicated location for storing persistent files, and another
location for storing cache data. The system prevents other apps from accessing these
locations and on Android 10 (API level 29) and higher, these locations are encrypted. These
characteristics make these locations a good place to store sensitive data that only your app
itself can access.

Fig. Internal Storage

Important Points about Internal Storage in Android:


o​ The stored data in memory is allowed to read and write files.
o​ When files are stored in internal storage these file can only be accessed by the
application itself not by other applications.
o​ These files in storage exist till the application stays over the device, as you uninstall
associated files get removed automatically.
o​ The files are stored in directory data/data which is followed by the application
package name.
o​ User can explicitly grant the permission to other apps to access files.
o​ To make the data private i.e you can use MODE_PRIVATE as discussed below about
the modes.
o​ Technique is best suited when data can only be access by the application neither by
the user nor by other apps.
o​ 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.
Android makes use of its internal storage for a variety of things:
­​ Operating System: The internal storage of the Android device houses the operating
system itself. The system files, libraries, and other elements required for the device
to operate are included in this.
­​ System Apps: The internal storage is where pre-installed system apps like the dialer,
messaging app, and settings are kept. The device's basic functionality depends on
these apps.
­​ User Data: User data is also kept in internal storage and is produced by apps and the
device itself. This includes downloaded files, game progress saved, programme
preferences, camera-captured media, and game saves.
Use Cases:
●​ Installing Apps: By default, apps downloaded from the Google Play Store or other
sources are installed on the device's internal storage. This guarantees that the apps
are available and incorporated into the system of the device.
●​ App Data Storage: To give customers a customised experience, apps save their data in
the internal storage. User profiles, preferences, settings, cached files, and locally
saved information can all be included in this data.
●​ System Updates: On the internal storage, significant OS upgrades and security
patches are downloaded as part of the Android system updates. To accommodate
these updates, the internal storage must have enough room.
●​ Device Backup: Backup feature is frequently included in Android smartphones,
enabling users to save their data, including settings and app data, to internal storage.
In the event of a device reset or when configuring a new device, this backup can be
restored.
●​ Storage for Offline Media: Internal storage can be used to store offline media assets,
including music, videos, and pictures. Even without a network connection or external
storage, users can still save and view these data.

Exploring the method used for internal storage


Saving and loading data on the internal storage is private for an application that cannot be
accessed by other applications. When the app is uninstalled the data stored in the internal
by that app is removed. To read and write in the Android internal storage we have two
methods –
●​ OpenFileOutput(): used for creating and saving a file. This method returns a
FileOutputStream instance.
Syntax:
OpenFileOutput(String filename,int mode)
●​ OpenFileInput(): Used to read data from a file, this returns a FileInputStream
instance.
Syntax:
OpenFileInput( String filename)

Write
Sr. No Method & description
1 FileOutputStream(File file, boolean append)
This method constructs a new FileOutputStream that writes to file.
2 getChannel()
This method returns a write-only FileChannel that shares its position with this stream
3 getFD()
This method returns the underlying file descriptor
4 write(byte[] buffer, int byteOffset, int byteCount)
This method Writes count bytes from the byte array buffer starting at position offset to
this stream

Read
Sr. No Method & description
1 available()
This method returns an estimated number of bytes that can be read or skipped without
blocking for more input
2 getChannel()
This method returns a read-only FileChannel that shares its position with this stream
3 getFD()
This method returns the underlying file descriptor
4 read(byte[] buffer, int byteOffset, int byteCount)
This method reads at most length bytes from this stream and stores them in the byte
array b starting at offset

Developing an application to save user data persistently in file


import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private TextViewsavedDataTextView;
private Button saveDataButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedDataTextView = findViewById(R.id.savedDataTextView);
saveDataButton = findViewById(R.id.saveDataButton);
saveDataButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String dataToSave = "Hello, this is user data!";
saveDataToFile(dataToSave);
String savedData = readDataFromFile();
savedDataTextView.setText("Saved Data: " + savedData);
Toast.makeText(MainActivity.this, "Saved Data: " + savedData, Toast.LENGTH_LONG).show();
}
});
}
private void saveDataToFile(String data) {
try {
FileOutputStreamfos = openFileOutput("user_data.txt", MODE_PRIVATE);
fos.write(data.getBytes());
fos.close(); // Close the stream
} catch (IOException e) {
e.printStackTrace();
}
}
private String readDataFromFile() {
StringBuilder stringBuilder = new StringBuilder();
try {
FileInputStreamfis = openFileInput("user_data.txt");
int character;
while ((character = fis.read()) != -1) {
stringBuilder.append((char) character);
}
fis.close(); // Close the stream
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString(); // Return the read data
}
}

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/savedDataTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Saved Data will appear here"
android:textSize="18sp"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:layout_alignParentTop="true" />
<Button
android:id="@+id/saveDataButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save and Read Data"
android:layout_centerHorizontal="true"
android:layout_below="@id/savedDataTextView"
android:layout_marginTop="20dp" />
</RelativeLayout>

External storage
Android storage of data/files in external storage or you can say the secondary memory/SD
card of your phone. 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.
Android gives various options for storing apps data which uses a file system similar to the
disk-based system on computer platforms-
●​ App-Specific storage: Store data files within internal volume directories or external.
These data files are meant only for the app’s use. It uses internal storage directories
to save sensitive information such as a username and password that other app
should not access.
●​ Shared Storage: Store data files such as images, audio, video, documents, etc. that
the app may need to share with other apps.
●​ Shared Preferences: Store primitive data type such as integer, float, Boolean, string,
long in key-value pairs.
●​ Databases: Store structured data such as user-information(name, age, phone, email,
address, etc.) into private databases.

Fig. External Storage


Use Cases:
o​ Media Storage: Media items including pictures, films, and music are frequently kept
in external storage. Direct media transfer from a computer or other device to an
external storage device frees up space on the internal storage and facilitates quick
access to media files for users.
o​ App Data Expansion: Some apps offer the option to use external storage for storing
more app data, particularly those that deal with huge volumes of data. This enables
users to save smaller files or material on the external storage while installing apps on
the internal storage.
o​ Offline Content: Users who want to access offline content without an internet
connection can store it on external storage. Users can save offline videos, maps, and
ebooks to the external storage and view them while they're not connected to the
internet.
o​ Backup and Transfer: External storage is a practical choice for transferring data
between devices and backing up crucial files. On a microSD card or USB drive, users
can store crucial files, paperwork, or backups, making it simple to move data to
different devices or carry out file restoration when necessary.

Exploring the method used for external storage


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.
●​ getExternalStoragePublicDirectory() : This is current recommended way that enable
us to keep files public and are not deleted with the app uninstallation. Example
images clicked by the camera exists even we uninstall the camera app.
To avoid crashing app it is required to check before whether storage SD card is available for
read & write operations. getExternalStorageState() method is used to determine the state of
the storage media i.e SD card is mounted, is it readable , it is writable etc.. all this kind of
information.
Example:
booleanisAvailable= false;
booleanisWritable= false;
booleanisReadable= false;
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state))
{
isAvailable= true;
isWritable= true;
isReadable= true;
}
else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
{
isAvailable= true;
isWritable= false;
isReadable= true;
}
else
{
isAvailable = false;
isWritable= false;
isReadable= false;
}
Developing an application to save file in SD card
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

import android.os.Bundle;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {

private static final int REQUEST_PERMISSION = 1;


private EditTextdataEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataEditText = findViewById(R.id.dataEditText);
Button saveDataButton = findViewById(R.id.saveDataButton);

saveDataButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String userInput = dataEditText.getText().toString().trim();
if (userInput.isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter some data", Toast.LENGTH_SHORT).show();
} else {
if (checkPermission()) {
saveDataToSDCard(userInput);
} else {
requestPermission();
}
}
}
});
}
private booleancheckPermission() {
int result = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED;
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new
String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION) {
if (grantResults.length> 0 &&grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
String userInput = dataEditText.getText().toString().trim();
saveDataToSDCard(userInput);
} else {
Toast.makeText(this, "Permission denied!", Toast.LENGTH_SHORT).show();
}
}
}
private void saveDataToSDCard(String data) {
if (isExternalStorageWritable()) {
File file = new File(Environment.getExternalStorageDirectory(), "user_data.txt");
try {
FileOutputStreamfos = new FileOutputStream(file);
fos.write(data.getBytes());
fos.close();
Toast.makeText(this, "Data saved to SD card", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Error saving file", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "External storage is not writable", Toast.LENGTH_SHORT).show();
}
}
private booleanisExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
}

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/dataEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter some data"
android:layout_marginTop="50dp"
android:padding="16dp" />
<Button
android:id="@+id/saveDataButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Data to SD Card"
android:layout_centerHorizontal="true"
android:layout_below="@id/dataEditText"
android:layout_marginTop="20dp" />
</RelativeLayout>

SQLite Database
Android SQLite is a very lightweight database which comes with Android OS. Android SQLite
combines a clean SQL interface with a very small memory footprint and decent speed. For
Android, SQLite is “baked into” the Android runtime, so every Android application can create
its own SQLite databases. Android SQLite native API is not JDBC, as JDBC might be too much
overhead for a memory-limited smartphone. Once a database is created successfully it
located in data/data/databases/ accessible from Android Device Monitor. SQLite is a
typical relational database, containing tables (which consists of rows and columns), indexes
etc. We can create our own tables to hold the data accordingly. This structure is referred to
as a schema.

Fig. SQLite

Creating And Updating Database In Android


For creating, updating and other operations you need to create a subclass
or SQLiteOpenHelper class. SQLiteOpenHelper is a helper class to manage database creation
and version management. It provides two methods onCreate(SQLiteDatabasedb),
onUpgrade(SQLiteDatabasedb, int oldVersion, int newVersion).
The SQLiteOpenHelper is responsible for opening database if exist, creating database if it
does not exists and upgrading if required. The SQLiteOpenHelper only require the
DATABASE_NAME to create database. After extending SQLiteOpenHelper you will need to
implement its methods onCreate, onUpgrade and constructor.
●​ onCreate(SQLiteDatabasesqLiteDatabase) method is called only once throughout the
application lifecycle. It will be called whenever there is a first call to
getReadableDatabase() or getWritableDatabase() function available in super
SQLiteOpenHelper class. So SQLiteOpenHelper class call the onCreate() method after
creating database and instantiate SQLiteDatabase object. Database name is passed in
constructor call.onUpgrade(SQLiteDatabasedb,intoldVersion, int newVersion) is only
called whenever there is a updation in existing version. So to update a version we
have to increment the value of version variable passed in the superclass constructor.
●​ In onUpgrade method we can write queries to perform whatever action is required.
In most example you will see that existing table(s) are being dropped and again
onCreate() method is being called to create tables again. But it’s not mandatory to do
so and it all depends upon your requirements.We have to change database version if
we have added a new row in the database table. If we have requirement that we
don’t want to lose existing data in the table then we can write alter table query in
the onUpgrade(SQLiteDatabasedb,intoldVersion, int newVersion) method.

Important Methods in SQLite Database:


Method Description
getColumnNames() This method is used to get the Array of column names of our
SQLite table.
getCount() This method will return the number of rows in the cursor.
isClosed() This method returns a Boolean value when our cursor is
closed.
getColumnCount() This method returns the total number of columns present in
our table.
getColumnName(int This method will return the name of the column when we
columnIndex) passed the index of our column in it.
getColumnIndex(String This method will return the index of our column from the
columnName) name of the column.
getPosition() This method will return the current position of our cursor in
our table.

Creating database helper class


SQLite Open Helper is an in-built class of android.database.sqlite.SQLiteDatabase
package. It is a helper class to manage SQLite database creation and version management.
The helper class manages the creation of the database, handling database manipulations,
and also the version management. We need to create a subclass extending from
SQLiteOpenHelper class for database manipulations. In this class, we will implement two
overridden methods onCreate( ) and onUpgrade( ). These classes take care of opening the
database if it exists, creating it if it does not, and upgrading it as necessary.
Syntax:
DatabaseHelper dbh= new DatabaseHelper(getApplicationContext());
public DatabaseHelper(Context context)
{
super(context,dbName,null,version);
context=this.context;
}

Example:
private Context context;
public DatabaseHelper(Context context)
{
super(context,dbName,null,version);
context=this.context;
}

Creating layout and activity for insert operation


AndroidManifest.xml:
<activity android:name=".InsertActivity"></activity>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name" />
<EditText
android:id="@+id/editTextAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Age"
android:inputType="number" />
<Button
android:id="@+id/buttonInsert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Insert" />
</LinearLayout>

DatabaseHelper.java:
package com.example.------;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "users.db";
private static final String TABLE_NAME = "users";
private static final String COL_1 = "ID";
private static final String COL_2 = "NAME";
private static final String COL_3 = "AGE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableSQL = "CREATE TABLE " + TABLE_NAME + " (" +
COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_2 + " TEXT, " +
COL_3 + " INTEGER)";
db.execSQL(createTableSQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, int age) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, name);
contentValues.put(COL_3, age);
long result = db.insert(TABLE_NAME, null, contentValues);
return result != -1; // Returns true if insertion is successful
}
}

Main_activity.java:
package com.example.insertoperation;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private EditText editTextName, editTextAge;
private Button buttonInsert;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = findViewById(R.id.editTextName);
editTextAge = findViewById(R.id.editTextAge);
buttonInsert = findViewById(R.id.buttonInsert);
buttonInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
insertData();
}
});
}
private void insertData() {
String name = editTextName.getText().toString();
String ageStr = editTextAge.getText().toString();
if (name.isEmpty() || ageStr.isEmpty()) {
Toast.makeText(this, "Please enter both name and age",
Toast.LENGTH_SHORT).show();
return;
}
int age = Integer.parseInt(ageStr);
DatabaseHelper databaseHelper = new DatabaseHelper(this);
boolean isInserted = databaseHelper.insertData(name, age);
if (isInserted) {
Toast.makeText(this, "Data inserted successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Data insertion failed", Toast.LENGTH_SHORT).show();
}
}
}

Write a program to Creating activity class to insert, search, fetch all records, update, delete
in android studio

Content provider
A content provider component supplies data from one application to others on
request. Such requests are handled by the methods of the Content Resolver class. A content
provider can use different ways to store its data and the data can be stored in a database, in
files, or even over a network.
Content providers let you centralize content in one place and have many different
applications access it as needed. A content provider behaves very much like a database
where you can query it, edit its content, as well as add or delete content using insert (),
update(), delete(), and query() methods. In most cases this data is stored in
an SQLite database.
A content provider is implemented as a subclass of ContentProvider class and must
implement a standard set of APIs that enable other applications to perform transactions.
Syntax:
public class My Application extends_ContentProvider
{
}

●​ Consider the structured data added to the device from application1 is not
accessible to another application2 present in the same device but the profile
photo added to the device by application1 is available to
the application2 running in the same device
●​ Consider android device as a city, the applications in it are the houses in the city,
people in the houses(application) are the data. Now content provider is like an
broker in the city(android device). This broker provide access for the people in
the city for finding different houses referring as the content provider in the
android device provide access for the data in the device for different
applications.

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>
Here is the detail of various parts of the URI −
Sr.N
Part & Description
o
prefix
1
This is always set to content://
authority
This specifies the name of the content provider, for example contacts, browser etc.
2
For third-party content providers, this could be the fully qualified name, such as
com.tutorialspoint.statusprovider
data_type
This indicates the type of data that this particular provider provides. For example,
3
if you are getting all the contacts from the Contacts content provider, then the
data path would be people and URI would look like thiscontent://contacts/people
id
This specifies the specific record requested. For example, if you are looking for
4
contact number 5 in the Contacts content provider then URI would look like this
content://contacts/people/5.

Create Content Provider


This involves number of simple steps to create your own content provider.
First of all, you need to create a Content Provider class that extends the
ContentProviderbaseclass.
Second, you need to define your content provider URI address which will be used to access
the content.
Next you will need to create your own database to keep the content. Usually,
Android uses SQLite database and framework needs to override onCreate() method which
will use SQLite Open Helper method to create or open the provider's database. When your
application is launched, the onCreate() handler of each of its Content Providers is called on
the main application thread.
Next you will have to implement Content Provider queries to perform different database
specific operations.
Finally register your Content Provider in your activity file using < provider > tag.
Here is the list of methods which you need to override in Content Provider class to have your
Content Provider working −
​­ 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.
Example:-
This example will explain you how to create your own Content Provider. So let's follow the
following steps to similar to what we followed while creating Hello World Example−
Step Description
You will use Android StudioIDE to create an Android application and name it as My
1
Application under a package com.example.MyApplication, with blank Activity.
Modify main activity file MainActivity.java to add two new methods onClickAddName()
2
and onClickRetrieveStudents().
Create a new java file called StudentsProvider.java under the package
3
com.example.MyApplication to define your actual provider and associated methods.
4 Register your content provider in your AndroidManifest.xml file using < provider.../> tag
Modify the default content of res/layout/activity_main.xml file to include a small GUI to
5
add students records.
6 No need to change string.xml.Android studio take care of string.xml file.
Run the application to launch Android emulator and verify the result of the changes
7
done in the application.

Exploring android.provider package


The content providers included with Android in the package android.provider.
1. MediaStore
2. CallLog
3. Browser
4. ContactsContract
5. Settings
6. UserDictionary

Using the MediaStoreContent Provider:


­​ You can use the MediaStore content provider to access media on the phone and on
external storage devices.
­​ The primary types of media that you can access are audio, images, and video.
­​ You can access these different types of media through their respective content
provider classes under android.provider.MediaStore.
­​ You can retrieve, add, and delete media files from the device.
­​ Syntax:
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
Using the CallLogContent Provider:
­​ Android provides a content provider to access the call log on the handset via the
class android.provider.CallLog.
­​ You can use the CallLog to filter recently dialed calls, received, and missed calls.
­​ The CallLog is a useful content provider for customer relationship management
(CRM) applications.
­​ Accessing Content Providers That Require Permissions:
android.permission.READ_CONTACTS
­​ Syntax:
Uri uri = CallLog.Calls.CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
Using the Browser Content Provider:
­​ The Browser content provider exposes the user’s browser site history and their
bookmarked websites.
­​ You access this con-tent provider via the android.provider.Browser class.
­​ You might use the Browser content provider to add a bookmark for your application
support website.
Using the Contacts Content Provider:
­​ People always want phone numbers handy for calling friends, family, co-workers, and
clients.
­​ Additionally, most phones show the identity of the caller based on the contacts
application, including nicknames, photos, or icons.
­​ Android provides a built-in Contact application, and the contact data is exposed to
other Android applications using the content provider interface.
­​ The content provider for accessing user contacts was originally called Contacts.
­​ This class, called ContactsContract, includes a sub-class called
ContactsContract.Contacts.
­​ This is preferred contacts content provider, as of API Level 5.
­​ Syntax:
Uri uri = ContactsContract.Contacts.CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
Using the UserDictionaryContent Provider:
­​ You can use this content provider for predictive text input on text fields and other
user input mechanisms.
­​ Individual words stored in the dictionary are weighted by frequency and organized by
locale.
­​ You can use the addWord() method within the UserDictionary.Words class to add
words to the custom user dictionary.
­​ Syntax:
Uri uri = UserDictionary.Words.CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
Using the SettingsContent Provider:
­​ You can use this content provider to access the device settings and user preferences.
­​ Settings are organized much as they are in the Settings application—by category.
­​ You can find information about the Settings content provider in the
android.provider.Settings class.
­​ Syntax:
int brightness = Settings.System.getInt(
getContentResolver(), Settings.System.SCREEN_BRIGHTNESS,-1);

Emailing in android
Easily send an email from our android application using existing email clients such
as GMAIL, Outlook, etc. instead of building an email client from scratch.Generally,
the Intent object in android with proper action (ACTION_SEND) and data will help us to
launch the available email clients to send an email in our application.In android, Intent is a
messaging object which is used to request an action from another app component such
as activities, services, broadcast receivers, and content providers.
ACTION_SEND - It’s an activity action that specifies that we are sending some data.
Syntax:
​ Intent emailIntent = new Intent(Intent.ACTION_SEND);
putExtra - we use this putExtra() method to add extra information to our Intent. Here we can
add the following things.
●​ EXTRA_EMAIL - It’s an array of email addresses
●​ EXTRA_SUBJECT - The subject of the email that we want to send
●​ EXTRA_TEXT - The body of the email

Android includes a built-in capability for adding TO, SUBJECT, CC, and TEXT fields which can
be attached to the Intent before sending the Intent to the targeted email client. We can
include the following extra fields in our Email as shown below.
●​ Intent.EXTRA_EMAIL: All "To" recipient email addresses are stored in this string array.
●​ Intent.EXTRA_CC: All "CC" recipient email addresses are stored in this string array.
●​ Intent.EXTRA_BCC: All "BCC" recipient email addresses are stored in this string array.
●​ Intent.EXTRA_SUBJECT: The email subject as a string.
●​ Intent.EXTRA_TEXT: A string containing the Email's body.
●​ Intent.EXTRA_STREAM: Uri directing attention to the attachment. Instead, this
should be an ArrayList containing multiple Uri objects If we are using
the ACTION_SEND_MULTIPLE action.
●​ EXTRA_TITLE: When used with an ACTION_CHOOSER, a CharSequence dialog title is
sent to the user.
Syntax:
●​ myEmailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"enter Recipient here"});
●​ myEmailIntent.putExtra(Intent.EXTRA_SUBJECT, "type subject here");
●​ myEmailIntent.putExtra(Intent.EXTRA_TEXT, "content of Message Body");
Building and application to send mail
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>​
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"​
android:layout_width="match_parent"​
android:layout_height="match_parent"​
android:paddingLeft="20dp"​
android:paddingRight="20dp"​
android:orientation="vertical" >​
<EditText​
android:id="@+id/txtTo"​
android:layout_width="match_parent"​
android:layout_height="wrap_content"​
android:hint="To"/>​
<EditText​
android:id="@+id/txtSub"​
android:layout_width="match_parent"​
android:layout_height="wrap_content"​
android:hint="Subject"/>​
<EditText​
android:id="@+id/txtMsg"​
android:layout_width="match_parent"​
android:layout_height="0dp"​
android:layout_weight="1"​
android:gravity="top"​
android:hint="Message"/>​
<Button​
android:layout_width="100dp"​
android:layout_height="wrap_content"​
android:layout_gravity="right"​
android:text="Send"​
android:id="@+id/btnSend"/>​
</LinearLayout>

MainActivity.java
package com.tutlane.sendmailexample;​
import android.content.Intent;​
import android.support.v7.app.AppCompatActivity;​
import android.os.Bundle;​
import android.view.View;​
import android.widget.Button;​
import android.widget.EditText;​
public class MainActivity extends AppCompatActivity
{​
private EditText eTo;​
private EditText eSubject;​
private EditText eMsg;​
private Button btn;​
@Override​
protected void onCreate(Bundle savedInstanceState)
{​
super.onCreate(savedInstanceState);​
setContentView(R.layout.activity_main);​
eTo = (EditText)findViewById(R.id.txtTo);​
eSubject = (EditText)findViewById(R.id.txtSub);​
eMsg = (EditText)findViewById(R.id.txtMsg);​
btn = (Button)findViewById(R.id.btnSend);​
btn.setOnClickListener(new View.OnClickListener()
{​
@Override​
public void onClick(View v)
{​
Intent it = new Intent(Intent.ACTION_SEND);​
it. putExtra(Intent.EXTRA_EMAIL, new String[]{eTo.getText().toString()});​
it.putExtra(Intent.EXTRA_SUBJECT,eSubject.getText().toString());​
it.putExtra(Intent.EXTRA_TEXT,eMsg.getText());​
it.setType("message/rfc822");​
startActivity(Intent.createChooser(it,"Choose Mail App"));​
}​
});​
}​
}
Output:

Networking in android
Networking in Android involves connecting apps to the internet or devices, enabling
data exchange, file downloading, and server communication. It supports APIs like HTTP,
TCP/IP, Bluetooth, and Wi-Fi. Understanding networking fundamentals is crucial, with
popular libraries like OkHttp, Retrofit, and Volley. Network connectivity changes can be
managed using Broadcast Receiver, and security measures like SSL/TLS protect data. Best
practices include caching, offline support, error handling, secure protocols, background
threads, and security measures. Networking is a great way to connect your application with
the world.Using Android Network Connectivity Services we can also determine the types of
a network of android device. It may be of types TYPE_WIFI (wifi),
TYPE_MOBILE (mobile), TYPE_BLUETOOTH (Bluetooth), etc.
Networking is an essential aspect of modern applications, allowing them to connect with
servers, databases, APIs, and other applications across the globe.
­​ Efficient Data Exchange: Networking allows you to exchange data efficiently with
browsers, databases, and other applications. APIs provide a modern approach for
two or more disparate applications to communicate or talk to each other.​
We will explain this later.
­​ Global Reach: Through networking, the application meets with a global audience
who can access its resources and services from anywhere in the world.
­​ Scalability: Networking supports the scalability of the applications.
­​ Integration: Networking allows applications to integrate with third-party APIs.

To access the network connectivity of a device, we need to provide the network access
permission in AndroidMenifest.xml file.
<usespermission android:name="android.permission.ACCESS_NETWORK_STATE" />
Sr.No Method & description
1 disconnect()
This method releases this connection so that its resources may be either reused
or closed
2 getRequestMethod()
This method returns the request method which will be used to make the request
to the remote HTTP server
3 getResponseCode()
This method returns response code returned by the remote HTTP server
4 setRequestMethod(String method)
This method Sets the request command which will be sent to the remote HTTP
server
5 usingProxy()
This method returns whether this connection uses a proxy server or not
Network Protocols in Android
Network protocols play a vital role in enabling communication between devices over a
network. In Android development, understanding different network protocols is essential for
building applications that can communicate effectively with servers and other devices. Let’s
explore some commonly used network protocols on Android and their significance in the
world of networking.
o​ HTTP (Hypertext Transfer Protocol): HTTP is the foundation of the World Wide Web
and is widely used for communication between web browsers and servers. It is a
request-response protocol, where the client sends a request to the server, and the
server responds with the requested data. In Android, HTTP is commonly used to
retrieve data from web APIs and display it in applications.
o​ HTTPS (Hypertext Transfer Protocol Secure): HTTPS is a secure version of HTTP that
encrypts data transmitted between the client and the server. It uses SSL/TLS
protocols to establish a secure connection, ensuring the confidentiality and integrity
of the data. HTTPS is essential for securing sensitive information, such as login
credentials and personal data, transmitted over the network in Android applications.
o​ TCP (Transmission Control Protocol): TCP is a reliable, connection-oriented protocol
that guarantees the delivery of data in the order it was sent. It provides
error-checking and flow control mechanisms, making it suitable for applications that
require reliable data transmission. In Android, TCP is often used for establishing
connections and transferring data between devices over the network.
o​ UDP (User Datagram Protocol): UDP is a connectionless, unreliable protocol that
does not guarantee the delivery of data or the order in which it is received. It is faster
and more lightweight than TCP but lacks reliability and error-checking features. UDP
is commonly used in applications where speed is more important than reliability,
such as real-time audio and video streaming.

Getting an overview of networking fundamentals


Connected states:
Sr.No State
1 Connecting
2 Disconnected
3 Disconnecting
4 Suspended
5 Unknown

Checking network availability


1.​ Add the ACCESS_NETWORK_STATE permission to your AndroidManifest.xml file to
allow your app to access information about the device's network connections:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>

2.​ Need to import the ConnectivityManager and NetworkInfo classes at the top of your
file:
import android.net.ConnectivityManager;​
import android.net.NetworkInfo;

3.​ Next, you will need to get a reference to the ConnectivityManager by


calling getSystemService() and passing in the CONNECTIVITY_SERVICE constant. This
will allow you to access information about the device's network connections.
4.​ ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

5.​ Then, you can use the getActiveNetworkInfo() method of


the ConnectivityManager to get a NetworkInfo an object representing the currently
active network connection, if one exists.
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
6.​ Then check if the device is connected to the internet by checking
the isConnectedOrConnecting() method of the NetworkInfo object. This method
returns true if the device is connected to the internet, and false if it is not.
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();

7.​ Finally, you can use an if statement to check the value of isConnected and take the
appropriate action based on the connection status.
if (isConnected) {​
// do something​
} else {​
// show an error message or do something else​
}

Web Server
A web service is basically required to provide interoperability, i.e. connecting various
applications. It allows different apps to communicate with each other and share the data
and services among themselves. Web services provide a standard for all the types of client
applications to invoke functions on every type of app server.
These refer to the various protocols that can be used in Android to exchange data,
interact with the web servers set up on the Internet and perform other various operation. By
implementing these, we can enable dynamic features that can rely on remote data and
services.

Accessing web servers using HTTP post


HTTP (Hyper Text Transfer Protocol) is the fundamental protocol used by the World Wide
Web to transfer and receive data. Android applications often need to communicate with
remote servers to send or retrieve data. One of the most common HTTP methods for
sending data to a server is the POST method.
What is HTTP POST?
The HTTP POST method is used to send data to a server, often in the form of a web
form submission or JSON data, and typically results in a change on the server (like creating a
new record in a database). Unlike the GET method, which appends data to the URL, the
POST method sends data in the body of the request. This allows for larger amounts of data
to be sent and makes the data more secure, as it is not visible in the URL.
HTTP POST Request Workflow
­​ Client Initiates Request
­​ Data Transmission
­​ Server Processes the Request
­​ Client Receives Response
Steps to access:-
-Add the required permission in the AndroidManifest.xml to access the internet
<uses-permission android:name="android.permission.INTERNET" />
-Create a method to make the HTTP request: Below is an example of how to send a simple
GET request using HttpURLConnection.
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "https://your-server.com/api/endpoint";
new GetRequestTask().execute(url);
}
private class GetRequestTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String urlString = params[0];
HttpURLConnection connection = null;
BufferedReader reader = null;
String response = null;

try {
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET"); // Set HTTP method
connection.setConnectTimeout(15000); // Set timeout
connection.setReadTimeout(15000);
reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
response = stringBuilder.toString(); // Response data
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response; }
@Override
protected void onPostExecute(String result) {
Log.d("Server Response", result);
}
}
}

Accessing web services using get method


Web Services for Android Networking use HTTP methods like GET, POST, PUT, and DELETE to
create a new request to these APIs and can perform the following operations:
●​ GET: Fetch data from API.
●​ POST: Adding new data to API.
●​ PUT: Updating existing data.
●​ DELETE: Deleting data on the server
The GET method to make HTTP requests and retrieve data from a server. To implement web
services using the GET method in Android, you typically use libraries such as
HttpURLConnection, OkHttp, or Retrofit.
How to use the GET method in Android?
Providing the key steps with concise syntax that clearly demonstrates your understanding.
Here's how you can write it for both HttpURLConnection and Retrofit.
1.​ HttpURLConnection (Low-level approach)
­​ Open a connection to the URL using HttpURLConnection.
­​ Set the request method to GET.
­​ Read the response using BufferedReader.
­​ Close the connection and resources after reading the response.
2.​ Retrofit (High-level approach)
­​ Define an interface with @GET annotation for the API endpoint.
­​ Create a Retrofit instance and configure it with a base URL and a converter (e.g.,
Gson).
­​ Call the API method using Retrofit's enqueue() for an asynchronous call.
Example:
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// URL of the web service (replace with your actual URL)
String urlString = "https://jsonplaceholder.typicode.com/posts/1"; // A sample URL for
testing
// Call AsyncTask to perform the network operation
new GetRequestTask().execute(urlString);
}
private class GetRequestTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String urlString = params[0];
HttpURLConnection connection = null;
BufferedReader reader = null;
String response = null;
try {
// Create URL object from the URL string
URL url = new URL(urlString);
// Open a connection to the server
connection = (HttpURLConnection) url.openConnection();
// Set request method to GET
connection.setRequestMethod("GET");
// Set timeouts for connection and reading
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
// Read the response
reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
response = stringBuilder.toString(); // Store the response in the 'response' variable
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response; // Return the response to the onPostExecute method
}
@Override
protected void onPostExecute(String result) {
// Process the response and log it (you can display it in the UI as well)
Log.d("GET Response", result);
}
}
}

Working with Binary Data


o​ A binary data is a file whose content is in a binary format consisting of a series of
sequential bytes, each of which is eight bits in length.
o​ Binary files are not human readable and require a special program or hardware
processor that knows how to read the data inside the file. Only then can the
instructions encoded in the binary content be understood and properly processed.
o​ Binary data is a sequence of bits (0s and 1s) organized into bytes (8 bits). For
example, an image file is essentially a collection of bytes that represent pixel data,
metadata, color information, etc.
o​ To make them suitable for storing complex data structures efficiently, in Java, we can
read from the write to binary files using the Input and Output Streams.
o​ Android provides various classes for handling binary data, including FileInputStream,
FileOutputStream, BufferedInputStream, and BufferedOutputStream, among others.
Below is a guide and examples of how to handle binary data (e.g., images, PDFs, etc.)
in Android.
o​ Android uses InputStream and OutputStream classes for reading and writing binary
data. FileInputStream: This class is used for reading raw binary data from a file. It
reads byte-by-byte or in chunks of bytes. FileOutputStream: This class is used for
writing raw binary data to a file. It writes byte-by-byte or in chunks.
o​ Many types of data, such as images, videos, and certain custom formats, are not
stored in human-readable text format. Instead, they are represented as binary data.
o​ Storing or transferring data in binary format is more efficient and ensures that the
data is not altered during the process (such as text encoding issues).

Syntax to Read from a Binary File:


InputStream ist = new FileInputStream("data.bin");​
int data;​
while ((data = ist.read()) != -1)
{
\\ code​
} ist.close();

Example:
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import java.io.FileInputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Path to the binary file we want to read (internal storage)
String filePath = getFilesDir() + "/sample_data.bin";

try {
// Read the binary data from the file using FileInputStream
FileInputStream fileInputStream = new FileInputStream(filePath);
int byteRead;
StringBuilder binaryDataRead = new StringBuilder();
// Read one byte at a time and append it to a StringBuilder
while ((byteRead = fileInputStream.read()) != -1) {
binaryDataRead.append(byteRead).append(" ");
}
fileInputStream.close();
// Log the read data
Log.d("File Read", "Binary data read: " + binaryDataRead.toString());

} catch (IOException e) {
e.printStackTrace();
}
}
}

Syntax to Write to a Binary File:


OutputStream ost= new FileOutputStream("data.bin");​
ost.close();

Example:
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Sample binary data to write (array of bytes)
byte[] binaryData = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // example data
// Path to save the binary file (internal storage)
String filePath = getFilesDir() + "/sample_data.bin";

try {
// Write the byte array to the file using FileOutputStream
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
fileOutputStream.write(binaryData); // Write the binary data
fileOutputStream.close();
Log.d("File Saved", "Binary data saved successfully at " + filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Working with text file


A text file in Android can be used for multiple functional purposes. It can be held privately to
store crucial information and sensitive data. It can also be used to store basic information
which the application, in various instances, can use. As text files pose no limits on input and
storage, they can serve as one of the most efficient methods of storing data.
­​ Create Text File – a folder in your sdcard will be created with an empty text file in it
(sdcard/MikeDalisayFolder/coan_log_file.txt)
­​ Read Text File – the contents of coan_log_file.txt text file will be shown in the screen,
you should click the update text file button first so it will have contents.
­​ Update Text File – it will update our text file with two lines of text.
­​ Delete Text File – it will delete our text file, of course. :)
Example:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
}
public void ReadTextFile(View view) throws IOException {
String string = "";
StringBuilder stringBuilder = new StringBuilder();
InputStream is = this.getResources().openRawResource(R.raw.sample);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while (true) {
try {
if ((string = reader.readLine()) == null) break;
}
catch (IOException e) {
e.printStackTrace();
}
stringBuilder.append(string).append("​
");
textView.setText(stringBuilder);
}
is.close();
Toast.makeText(getBaseContext(), stringBuilder.toString(),
Toast.LENGTH_LONG).show();
}
}

Example: Write to a Text File (External Storage)


import android.os.Environment;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtils {

public void writeToExternalFile(String data, String fileName) {


if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// Get the external storage directory
File directory = new File(Environment.getExternalStorageDirectory(), "MyAppFiles");

if (!directory.exists()) {
directory.mkdirs(); // Create the directory if it doesn't exist
}

File file = new File(directory, fileName);


try {
// Create a file output stream to write data
FileOutputStream fos = new FileOutputStream(file);
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Consuming JSON services


JSON stands for JavaScript Object Notation. It is an independent data exchange
format and is the best alternative for XML. This chapter explains how to parse the JSON file
and extract necessary information from it. JSON is used for data interchange (posting and
retrieving) from the server. Hence knowing the syntax and it’s usability is important. JSON is
the best alternative for XML and its more readable by human. JSON is language
independent. Because of language in-dependency we can program JSON in any language
(Java/C/C++). A JSON response from the server consists of many fields. An example JSON
response/data is given below. We’ll use it as a reference and implement it in our
application.Android provides four different classes to manipulate JSON data. These classes
are JSONArray,JSONObject,JSONStringer and JSONTokenizer.

JSON Elements In Android:


In Android, JSON consist of many components. Below we define some common
components.
1. Array([): In a JSON, square bracket ([) represents a JSONArray. JSONArray values may be
any mix of JSONObjects, other JSONArrays, Strings, Booleans, Integers, Longs, Doubles, null
or NULL. Values may not be NaNs, infinities, or of any type not listed here.
2. Objects({): In a JSON, curly bracket ({) represents a JSONObject. A JSONObject represents
the data in the form of key and value pair. JSONObject values may be any mix of other
JSONObjects, JSONArrays, Strings, Booleans, Integers, Longs, Doubles, null or NULL. Values
may not be NaNs, infinities, or of any type not listed here.
3. key: A JSONObject contains a key that is in string format. A pair of key and value creates a
JSONObject.
4. Value: Each key has a value that could be primitive datatype(integer, float, String etc).

Methods:
Sr.No Method & description
1 get(String name)
This method just Returns the value but in the form of Object type
2 getBoolean(String name)
This method returns the boolean value specified by the key
3 getDouble(String name)
This method returns the double value specified by the key
4 getInt(String name)
This method returns the integer value specified by the key
5 getLong(String name)
This method returns the long value specified by the key
6 length()
This method returns the number of name/value mappings in this object..
7 names()
This method returns an array containing the string names in this object.
Example:

Sockets programming
Socket programming is a way for devices to communicate over a network. Two sockets
communicate, one on the client-side and one on the server-side.
A socket’s address consists of an IP and a port. The server application starts to listen to
clients over the defined port. The client establishes a connection over the IP of the server
and the port it opens. The communication can then continue directionally.

​ Fig. Sockets

Socket programming is a frequently preferred method in IoT applications. Devices


communicate on the network. It is an environment-independent method as the
communication is provided over the TCP / IP protocol. Thus, a PLC can communicate with
an Android device as well as an Arduino can communicate with a Linux machine.
Categories function between client end servers:
A socket is a communications connection point (endpoint) that you can name and
address in a network. Socket programming shows how to use socket APIs to establish
communication links between remote and local processes. In the following example process
or steps of two sockets communicate. It works like client server architecture.

Fig. Socket programming

You might also like