Android Unit - 4
Android 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.
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.
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();
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
@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
}
}
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.
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 {
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);
}
}
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
Example:
private Context context;
public DatabaseHelper(Context context)
{
super(context,dbName,null,version);
context=this.context;
}
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.
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.
2. Need to import the ConnectivityManager and NetworkInfo classes at the top of your
file:
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
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.
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);
}
}
}
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();
}
}
}
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();
}
}
}
if (!directory.exists()) {
directory.mkdirs(); // Create the directory if it doesn't exist
}
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