Updated Chapter 5
Updated Chapter 5
Intent
Android uses Intent for communicating between the components of an Application and also from one
application to another application.
Intent are the objects which is used in android for passing the information among Activities in an
Application and from one app to another also.
Intent are used for communicating between the Application components and it also provides the
connectivity between two apps.
Intent are of two types:
Explicit Intent
Implicit Intent
Explicit Intent:
Explicit Intents are used to connect the application internally.
In Explicit we use the name of component which will be affected by Intent.
If we know class name then we can navigate the app from One Activity to another activity using Intent.
Explicit Intent work internally within an application to perform navigation and data transfer.
Implicit Intent:
In Implicit Intents we do need to specify the name of the component. We just specify the
Action which has to be performed and further this action is handled by the component of
another application.
The basic example of implicit Intent is to open any web page
activity_main.xml
<RelativeLayout
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Explicit Intent Example"
android:id="@+id/b1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Implicit Intent Example"
android:id="@+id/b2"/>
</RelativeLayout>
activity_second.xml
<RelativeLayout
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Second Activity"
android:id="@+id/textView" />
</RelativeLayout>
B1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
Intent in = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(in);
}
});
B2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SecondActivity.java
Intent Filter are the components which decide the behavior of an intent.Intent filters specify the type
of intents that an Activity, service or Broadcast receiver can respond to. It declares the functionality
of its parent component. The code of Intent Filter is used inside AndroidManifest.xml file for an
activity. You can see it: open manifests folder >> open AndroidManifest.xml file
Example 2:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:id="@+id/f1"
tools:context=".login">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Intent"
android:textSize="20dp"
android:gravity="center"/>
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text"
android:layout_marginTop="35dp"
android:text="Next page" />
<EditText
android:id="@+id/url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginTop="41dp"
android:hint="Enter URL" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginTop="167dp"
android:text="Google" />
</RelativeLayout>
Java File
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent in=new Intent(getApplicationContext(),secondPage.class);
startActivity(in);
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str=editText.getText().toString();
Intent in=new Intent(Intent.ACTION_VIEW);
in.setData(Uri.parse("https://"+str));
startActivity(in);
}
});
}
}
Example:
Java File
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
b=findViewById(R.id.b1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_DIAL);
startActivity(i);
}
});
}
}
Example:
Java File
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
<TextView
android:id="@+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textAlignment="center"
android:textSize="100px"
android:textStyle="bold"/>
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/t1"
android:layout_centerHorizontal="true"
android:text="BACK"/>
</RelativeLayout>
Java File
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
b=findViewById(R.id.b1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(login.this,MainActivity.class);
startActivity(i);
}
});
}
}
Activity Lifecycle
onCreate()
This is the first callback and called when the activity is first created.
onStart()
This callback is called when the activity becomes visible to the user.
onResume()
This is called when the user starts interacting with the application.
onPause()
The paused activity does not receive user input and cannot execute any code and called when the
current activity is being paused and the previous activity is being resumed.
onStop()
This callback is called when the activity is no longer visible.
onDestroy()
This callback is called before the activity is destroyed by the system.
onRestart()
This callback is called when the activity restarts after stopping it.
Example:
When you open the app it will go through below states:
onCreate() –> onStart() –> onResume()
When you press the back button and exit the app
onPaused() — > onStop() –> onDestory()
When you press the home button
onPaused() –> onStop()
After pressing the home button, again when you open the app from a recent task list
onRestart() –> onStart() –> onResume()
After dismissing the dialog or back button from the dialog
onResume()
If a phone is ringing and user is using the app
onPause() –> onResume()
After the call ends
onResume()
When your phone screen is off
onPaused() –> onStop()
When your phone screen is turned back on
onRestart() –> onStart() –> onResume()
Example:
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
@Override
protected void onStart() {
super.onStart();
Log.d("Life cycle","start method");
}
@Override
protected void onResume() {
super.onResume();
Log.d("Life cycle","Resume method");
}
@Override
protected void onPause(){
super.onPause();
Log.d("Life cycle","pause method");
}
@Override
protected void onStop(){
super.onStop();
Log.d("Life cycle","stop method");
}
@Override
public void onDestroy(){
super.onDestroy();
Log.d("Life cycle","destroy method");
}
@Override
public void onRestart(){
super.onResort();
Log.d("Life cycle","Restart method");
}
Broadcast Lifecycle
A broadcast receiver is a dormant component of the Android system.
The Broadcast Receiver’s job is to pass a notification to the user, in case a specific event
occurs.
Using a Broadcast Receiver, applications can register for a particular event.
Once the event occurs, the system will notify all the registered applications.
Example :
Steps:
Right click on package and select new
1) Select Other option
2) Select BroadcastReceiver
3) Give name to file
Example:
MyReceiver.java
package com.example.ifcdiv;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
@Override
public void onReceive(Context context, Intent intent) {
String actionstring=intent.getAction();
Toast.makeText(context,actionstring,Toast.LENGTH_LONG).show();
}
}
MainActivity.java
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
this.registerReceiver(myReceiver,intentFilter);
@Override
protected void onStop() {
super.onStop();
this.unregisterReceiver(myReceiver);
}
}
The second parameter is the name of the song that you want to play.
You have to make a new folder under your project with name raw and place the music file
into it.
Once you have created the Mediaplayer object you can call some methods to start or stop the
music.
These methods are listed below.
mediaPlayer.start();
mediaPlayer.pause();
On call to start() method, the music will start playing from the beginning.
If this method is called again after the pause() method, the music would start playing from
where it is left and not from the beginning.
In order to start music from the beginning, you have to call reset() method. Its syntax is given
below.
mediaPlayer.reset();
Example
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="40dp"
android:orientation="horizontal"
tools:context=".MainActivity">
<TextView
android:id="@+id/headingText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:text="MEDIA PLAYER"
android:textSize="18sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/headingText"
android:layout_marginTop="16dp"
android:gravity="center_horizontal">
<Button
android:id="@+id/stopButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:text="STOP"
android:textColor="@android:color/white" />
<Button
android:id="@+id/playButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:text="PLAY"
android:textColor="@android:color/white" />
<Button
android:id="@+id/pauseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PAUSE"
android:textColor="@android:color/white" />
</LinearLayout>
</RelativeLayout>
File: MainActivity.java
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
mp = MediaPlayer.create(this,R.raw.sheeran);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
mp.stop();
mp.prepare();
}catch (IOException e)
{
e.printStackTrace();
}
}
});
}
}
<VideoView
android:id="@+id/videoView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="0dp"
android:layout_marginBottom="0dp"/>
</RelativeLayout>
File: MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
<TextView
android:id="@+id/t1"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="150px"
android:text="Video Capturing"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open"
android:id="@+id/btn"
android:layout_below="@id/t1"
android:layout_centerHorizontal="true"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_below="@+id/btn"
>
<VideoView
android:layout_width="match_parent"
android:layout_height="400dp"
android:gravity="bottom"
android:layout_gravity="center_horizontal"
android:id="@+id/vv"
/>
</FrameLayout>
</RelativeLayout>
MainActivity.java
package com.example.myapplication;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.VideoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
vv = findViewById(R.id.vv);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(i,REQ);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode ==REQ) {
Uri videoUri = intent.getData();
vv.setVideoURI(videoUri);
vv.start();
}
}
Text to speech
@Override
}});
ttobj.setLanguage(Locale.UK);
Example:
public class MainActivity extends Activity {
TextToSpeech t1;
EditText ed1;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
b1=(Button)findViewById(R.id.button);
t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.UK);
}
}
});
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = ed1.getText().toString();
t1.speak(str, TextToSpeech.QUEUE_FLUSH, null);
}
});
}
Service
Features of Service
A service is a component that runs in the background to perform long-running operations without
needing to interact with the user.
A service is simply a component that can run in the background, even when the user is not
interacting with your application.
1. Started Service
A service becomes started only when an application component calls startService(). It performs a single
operation and doesn’t return any result to the caller. Once this service starts, it runs in the background
even if the component that created it destroys. This service can be stopped only in one of the two cases:
A service is bound only if an application component binds to it using bindService(). It gives a client-
server relation that lets the components interact with the service. The components can send requests to
services and get results.
The onBind() is called when another Thread registers to connect to the Service so that they can
communicate.
1. onStartCommand()
The system calls this method whenever a component, say an activity requests ‘start’ to a service,
using startService().
Once we use this method it’s our duty to stop the service using stopService() or stopSelf().
2. onBind()
This is invoked when a component wants to bind with the service by alling bindService(). In this, we
must provide an interface for clients to communicate with the service. For interprocess communication,
we use the IBinder object.
It is a must to implement this method. If in case binding is not required, we should return null as
implementation is mandatory.
3. onUnbind()
The system invokes this when all the clients disconnect from the interface published by the service.
4. onRebind()
The system calls this method when new clients connect to the service. The system calls it after
the onBind() method.
5. onCreate()
This is the first callback method that the system calls when a new component starts the service. We need
this method for a one-time set-up.
6. onDestroy()
This method is the final clean up call for the system. The system invokes it just before the service
destroys. It cleans up resources like threads, receivers, registered listeners, etc.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SERVICE"
android:textSize="60dp"
android:id="@+id/T1"
android:layout_centerHorizontal="true"
/>
<Button
android:id="@+id/B1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="120dp"
android:text="Start Service"
android:textSize="20dp" />
<Button
android:id="@+id/B2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="100dp"
android:text="Stop Service"
android:textSize="20dp"
android:layout_below="@+id/B1"/>
</RelativeLayout>
MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
B1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),MyService.class);
startService(intent);
}
});
B2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),MyService.class);
stopService(intent);
}
});
Create MyService.java
package com.example.ifcdiv;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;
@Override
public void onCreate() {
Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.setLooping(true);
player.start();
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
player.stop();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}
Camera
These are the following two ways, in which you can use camera in your application
1. By Camera Intent
2. By Camera API
Intent
By the help of 2 constants of MediaStore class, we can capture picture and video without using the
instance of Camera class.
1. ACTION_IMAGE_CAPTURE
2. ACTION_VIDEO_CAPTURE
Example
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="40dp"
android:orientation="horizontal"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="CAMERA"
android:id="@+id/text"
android:textSize="20dp"
android:gravity="center"/>
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text"
android:layout_marginTop="81dp"
android:src="@drawable/rose"/>
<Button
android:id="@+id/photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/image"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="TAKE PHOTO" />
</RelativeLayout>
Java File
package com.example.ifcdiv;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
b1=findViewById(R.id.photo);
imageView=findViewById(R.id.image);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==CAMERA_REQUEST)
{
Bitmap image= (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(image);
}
}
}
BlueTooth
Bluetooth is a way to exchange data with other devices wirelessly. Android provides Bluetooth API to
perform several tasks such as:
Menifest File:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ifcdiv">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.IFCDiv">
<activity android:name=".ttp"></activity>
<activity android:name=".login" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Java File
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button on,off,dis;
int REQUEST_ENABLE=0;
int REQUEST_DIS=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
on=findViewById(R.id.on);
off=findViewById(R.id.off);
dis=findViewById(R.id.discoverable);
BluetoothAdapter ba=BluetoothAdapter.getDefaultAdapter();
on.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!ba.isEnabled())
{
Intent i=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(i,REQUEST_ENABLE);
}
}
});
dis.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!ba.isDiscovering())
{
Intent i=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(i,0);
}
}
});
off.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ba.disable();
}
});
}
}
XML file :
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BlueTooth"
>
<Button
android:id="@+id/on"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="On" />
<Button
android:id="@+id/off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Off"
android:layout_below="@id/on"
/>
<Button
android:id="@+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Devices"
android:layout_centerHorizontal="true"
android:layout_below="@id/off"
/>
<TextView
android:id="@+id/res"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Devices:"
android:textSize="30dp"
android:layout_below="@id/list"
/>
</RelativeLayout>
Java file :
package com.example.travel_mate;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import java.util.Set;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blue_tooth);
on = findViewById(R.id.on);
off = findViewById(R.id.off);
list = findViewById(R.id.list);
tv = findViewById(R.id.res);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Turn ON Bluetooth
on.setOnClickListener(v -> {
if (!mBluetoothAdapter.isEnabled()) {
if (checkPermission()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
} else {
Toast.makeText(BlueTooth.this, "Bluetooth is already ON",
Toast.LENGTH_SHORT).show();
}
});
// Turn OFF Bluetooth
off.setOnClickListener(v -> {
if (mBluetoothAdapter.isEnabled()) {
Intent intent = new
Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
startActivity(intent);
Toast.makeText(BlueTooth.this, "Go to settings to turn off Bluetooth",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(BlueTooth.this, "Bluetooth is already OFF",
Toast.LENGTH_SHORT).show();
}
});
if (devices.size() > 0) {
for (BluetoothDevice device : devices) {
tv.append("\n\nDevice: " + device.getName() + " - " +
device.getAddress());
}
} else {
tv.setText("No paired Bluetooth devices found.");
}
});
}
Wifi
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="WiFi"
android:id="@+id/text"
android:textSize="20dp"
android:gravity="center"/>
<Button
android:id="@+id/on"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text"
android:layout_marginTop="62dp"
android:text="ON" />
<Button
android:id="@+id/off"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/on"
android:layout_marginTop="104dp"
android:text="OFF" />
</RelativeLayout>
Manifest File
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ifcdiv">
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.IFCDiv">
<activity android:name=".ttp"></activity>
<activity android:name=".login" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Java File
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
on=findViewById(R.id.on);
off=findViewById(R.id.off);
on.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WifiManager wifi= (WifiManager)
getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
});
off.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WifiManager wifi= (WifiManager)
getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);
}
});
Fragment
Android Fragment is the part of activity, it is also known as sub-activity. There can be more than one
fragment in an activity.
Fragments represent multiple screen inside one activity.
We can create Fragments by extending Fragment class or by inserting a Fragment into our Activity
layout by declaring the Fragment in the activity’s layout file, as a <fragment> element.
Fragments were added in Honeycomb version of Android i.e API version 11.
We can add, replace or remove Fragment’s in an Activity while the activity is running.
Fragment can be used in multiple activities.
We can also combine multiple Fragments in a single activity to build a multi-plane UI.
We can only show a single Activity on the screen at one given point of time so we were not able to
divide the screen and control different parts separately. With the help of Fragment’s we can divide the
screens in different parts and controls different parts separately.
Example:
Develop programs for implementing fragments.
- activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<fragment
android:id="@+id/Frag1"
android:layout_width="match_parent"
android:layout_height="400dp"
android:name="com.example.al_libaansapp"/>
<fragment
android:id="@+id/Frag2"
android:layout_width="match_parent"
android:layout_height="400dp"
android:name="com.example.al_libaansapp"/>
</LinearLayout>
- Fragment1.xml:
</FrameLayout>
- Fragment2.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/purple"
tools:context=".Fragment2">
</FrameLayout>
- Output:
Example (Tabbed Activity with fragment :
Fragment in Tabbed Activity
Steps:
1 Create the tabbed Activity
2 Create 3 java files and xml files as shown in diagram
3 Design the xml files (Ex fragment1_layout.xml)
Fragnent1.java
package com.example.tabbedfragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
Fragnent2.java
package com.example.tabbedfragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
Fragnent3.java
package com.example.tabbedfragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.content.Context;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.tabbedfragment.Fragment1;
import com.example.tabbedfragment.Fragment2;
import com.example.tabbedfragment.Fragment3;
import com.example.tabbedfragment.R;
@StringRes
private static final int[] TAB_TITLES = new int[]
{R.string.tab_text_1,R.string.tab_text_2,R.string.tab_text_3};
private final Context mContext;
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
@Override
public int getCount() {
return 3;
}
}
Animation
Animation is the process of creating motion and shape change.
1 View Animation:
It define the properties of our Views that should be animated using a technique called Tween
Animation.
It take the following parameters i.e. size, time duration , rotation angle, start value , end value, and
perform the required animation on that object.
Android View animation can make animation on any View objects, such as ImageView, TextView
or Button objects.
2 Property Animation:
Property animations are highly customizable, we can specify the duration, the number of repeats,
the type of interpolation, and the frame rate of the animation.
The Property Animation system is always preferred for more complex animations.
A property animation changes a property's (a field in an object) value over a specified length
of time.
To animate something, you specify the object property that you want to animate, such as an
object's position on the screen, how long you want to animate it for, and what values you want to
animate between.
3 Drawable Animation:
This animation allows the user to load drawable resources and display them one frame after
another.
This method of animation is useful when user wants to animate things that are easier to represent
with Drawable resources.
Note the second parameter. It is the name of the our animation xml file.
You have to create a new folder called anim under res directory and make an xml file under
anim folder.
This animation class has many useful functions which are listed below –
start()
This method starts the animation.
setDuration(long duration)
This method sets the duration of an animation.
getDuration()
This method gets the duration which is set by above method
end()
This method ends the animation.
cancel()
This method cancels the animation.
In order to apply this animation to an object , we will just call the startAnimation() method of the
object.
Its syntax is
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="clockwise"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_centerHorizontal="true"
android:onClick="clockwise"/>
</RelativeLayout>
res/anim/clockwise.xml.
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" >
</rotate>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="5000"
android:fromDegrees="360"
android:toDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000" >
</rotate>
</set>
Sensor
Most of the android devices have built-in sensors that measure motion, orientation, and various
environmental condition. The android platform supports three broad categories of sensors.
Motion Sensors
These are used to measure acceleration forces and rotational forces along with three axes.
Environmental sensors
These are used to measure the environmental changes such as temperature, humidity etc.
Position sensors
These are used to measure the physical position of device.
Some of the sensors are hardware based and some are software based sensors. Whatever the sensor is,
android allows us to get the raw data from these sensors and use it in our application.
Android provides SensorManager and Sensor classes to use the sensors in our application.
1) SensorManager class
The SensorManager class provides methods :
o to get sensor instance,
o to access and list sensors,
o to register and unregister sensor listeners etc.
You can get the instance of SensorManager by calling the method getSystemService() and passing the
SENSOR_SERVICE constant in it.
SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
2) Sensor class
The Sensor class provides methods to get information of the sensor such as sensor name, sensor type,
sensor resolution, sensor type etc.
3) SensorEvent class
Its instance is created by the system. It provides information about the sensor.
4) SensorEventListener interface
It provides two call back methods to get information when sensor values (x,y and z) change or sensor
accuracy changes.
Table 1. Sensor types supported by the Android platform.
Sensor Type Description Common Uses
Example
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="40dp"
android:orientation="horizontal"
tools:context=".MainActivity">
<TextView android:id="@+id/text"
android:textSize="20sp"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Java File
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
@Override
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
text.setText("x: "+values[0]+"\ny: "+values[1]+"\nz: "+values[2]);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Multimedia Framework
The android multimedia system includes multimedia applications, multimedia framework,
OpenCore engine and hardware abstract for audio/video input/output devices.
The goal of the android multimedia framework is to provide a consistent interface for Java services.
The multimedia framework consists of several core dynamic libraries such as libmediajni, libmedia,
libmediaplayservice and so on
Java classes call the Native C library Libmedia through Java JNI (Java Native Interface).
Libmedia library communicates with Media Server guard process through Android’s Binder IPC
(inter process communication) mechanism.
Media Server process creates the corresponding multimedia service according to the Java
multimedia applications. The whole communication between Libmedia and Media Server forms a
Client/Server model.
In Media Server guard process, it calls OpenCore multimedia engine to realize the specific
multimedia processing functions. And the OpenCore engine refers to the PVPlayer and PVAuthor.
SQLite Database
SQLite is an open-source relational database i.e. used to perform database operations on
android devices such as storing, manipulating or retrieving persistent data from the database.
It is embedded in android bydefault. So, there is no need to perform any database setup or
administration task.
SQLite is one way of storing app data. It is very lightweight database that comes with Android
OS.
By default, Android comes with built-in SQLite Database support so we don’t need to do any
configurations.
Android stores our database in a private disk space that’s associated with our application and
the data is secure, because by default this area is not accessible to other applications.
The package android.database.sqlite contains all the required APIs to use an SQLite database in
our android applications.
In android, by using SQLiteOpenHelper class we can easily create the required database and
tables for our application. To use SQLiteOpenHelper, we need to create a subclass that
overrides the onCreate() and onUpgrade() call-back methods.
onCreate(): This method is called only once throughout the application after the database is
created
onUpgrade():This method is called whenever there is an updation in the database like
modifying the table structure, adding constraints to the database, etc.
We can insert data into the SQLite database by passing ContentValues to insert() method.
In android, we can read the data from the SQLite database using the query() method in android
applications.
We can update the data in the SQLite database using an update() method in android
applications.
Example:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Registration Form"
android:layout_centerHorizontal="true"
android:textSize="40dp"
android:textStyle="bold"
android:layout_margin="20dp" />
<EditText
android:id="@+id/rollNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Enter Roll No:"
android:textSize="30dp"
android:layout_margin="20dp" />
<EditText
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Enter Name:"
android:layout_below="@id/rollNo"
android:layout_margin="20dp"
android:textSize="30dp" />
<Button
android:id="@+id/insert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_centerInParent="true"
android:text="Insert" />
<Button
android:id="@+id/update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/insert"
android:layout_centerInParent="true"
android:text="Update" />
<Button
android:id="@+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/update"
android:layout_centerInParent="true"
android:text="Delete" />
<Button
android:id="@+id/view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/delete"
android:layout_centerInParent="true"
android:text="View" />
</RelativeLayout>
MainActivity.java
package com.example.updateddatabase;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
insert = findViewById(R.id.insert);
update = findViewById(R.id.update);
delete = findViewById(R.id.delete);
view = findViewById(R.id.view);
rollNo = findViewById(R.id.rollNo);
name = findViewById(R.id.name);
db=new DatabaseHelper(this);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String rn = rollNo.getText().toString();
String nm = name.getText().toString();
if (res) {
Toast.makeText(getApplicationContext(), "Inserted!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Error Inserting!",
Toast.LENGTH_LONG).show();
}
}
});
update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String rn = rollNo.getText().toString();
String nm = name.getText().toString();
if (res) {
Toast.makeText(getApplicationContext(), "Updated!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Error Updating!",
Toast.LENGTH_LONG).show();
}
}
});
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String rn = rollNo.getText().toString();
if (res) {
Toast.makeText(getApplicationContext(), "Deleted!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Error Deleting!",
Toast.LENGTH_LONG).show();
}
}
});
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
Cursor res = db.getData();
StringBuffer sb = new StringBuffer();
while(res.moveToNext()) {
sb.append("Roll No: " + res.getString(0) + "\n");
sb.append("Name: " + res.getString(1) + "\n\n");
}
}
}
DatabaseHelper.java
package com.example.updateddatabase;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE students(rollNo TEXT primary key, name TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS students");
}
cv.put("rollNo", rn);
cv.put("name", nm);
if (res != -1) {
return true;
}
else return false;
}
cv.put("name", nm);
if (res != -1) {
return true;
} else return false;
}
if (res != -1) {
return true;
} else return false;
}
MainActivity.java:
package com.example.database2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
SQLiteDatabase sqldb;
Button create;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
create = findViewById(R.id.create);
create.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sqldb = openOrCreateDatabase("students2", Context.MODE_PRIVATE, null);
Content Provider
A Content Provider component supplies data from one application to others on request.
Such requests are handled by the methods of the ContentResolver class.
A content provider can use different ways to store its data and the data can be stored in files, in
a database or even over a network.
Content Providers support the four basic operations, normally called CRUD-operations. (Create
,Read ,Update,Delete)
With content providers those objects simply represent data as most often a record of a database,
but they could also be a photo on our SD-card or a video on the web.
Whenever we want to access data from a content provider we have to specify a URI.
URIs for content providers look like this:
content://authority/optionalPath/optionalId
Two types of URI
directory-based URIs
id-based URIs
1. CalendarContract SDK 14: Manages the calendars on the user’s device.
2. Browser SDK 1: Manages our web-searches, bookmarks and browsing-history.
3. CallLog SDK 1: Keeps track of our call history.
4. MediaStore SDK 1: The content provider responsible for all our media files like music,
video and pictures.
5. Settings SDK 1: Manages all global settings of our device.
6. UserDictionary SDK 3: Keeps track of words we add to the default dictionary.
Example:
Accessing contact list
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="40dp"
android:orientation="vertical"
tools:context=".MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listview"/>
</LinearLayout>
Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ifcdiv">
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.IFCDiv">
</manifest>
MainActivity.java
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
listView=findViewById(R.id.listview);
listdata=new ArrayList<String>();
fetchdata();
}
private void fetchdata()
{
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!=
PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,new String[]
{Manifest.permission.READ_CONTACTS},0);
ContentResolver resolver=getContentResolver();
Uri uri= ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection=null;
String selection=null;
String[] selectionArg=null;
String order=null;
Cursor cursor=resolver.query(uri,projection,selection,selectionArg,order);
if(cursor.getCount()>=0)
{
while (cursor.moveToNext())
{
String
name=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_
NAME));
String
number=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBE
R));
String phoneNumber=name+"\n"+number;
listdata.add(phoneNumber);
}
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,listdata);
listView.setAdapter(adapter);
}
Example :
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_marginBottom="70dp"
android:text="Content Provider"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textSize="36sp"
android:textStyle="bold" />
<EditText
android:id="@+id/textName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:hint="Enter name"
android:layout_marginEnd="20dp"
android:layout_marginBottom="40dp"/>
<Button
android:id="@+id/insertButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:onClick="onClickAddDetails"
android:text="Add details"
android:textStyle="bold" />
<Button
android:id="@+id/loadButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:onClick="onClickShowDetails"
android:text="Display details"
android:textAlignment="center"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<TextView
android:id="@+id/res"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:clickable="false"
android:ems="10"
android:textColor="@android:color/holo_green_dark"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
MyContentProvider.java
package com.example.sensor;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import java.util.HashMap;
static {
// to match the content URI
// every time user access table under content provider
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case uriCode:
count = db.delete(TABLE_NAME, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case uriCode:
return "vnd.android.cursor.dir/users";
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
long rowID = db.insert(TABLE_NAME, "", values);
if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLiteException("Failed to add a record into " + uri);
}
@Override
public boolean onCreate() {
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
db = dbHelper.getWritableDatabase();
if (db != null) {
return true;
}
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(TABLE_NAME);
switch (uriMatcher.match(uri)) {
case uriCode:
qb.setProjectionMap(values);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (sortOrder == null || sortOrder == "") {
sortOrder = id;
}
Cursor c = qb.query(db, projection, selection, selectionArgs, null,
null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int count = 0;
switch (uriMatcher.match(uri)) {
case uriCode:
count = db.update(TABLE_NAME, values, selection, selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
// creating object of database
// to perform query
private SQLiteDatabase db;
// creating a database
private static class DatabaseHelper extends SQLiteOpenHelper {
// defining a constructor
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// creating a table in the database
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_DB_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
MainActivity.java
package com.example.sensor;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_marginBottom="70dp"
android:text="Content Provider"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
android:textSize="36sp"
android:textStyle="bold" />
<Button
android:id="@+id/loadButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:onClick="onClickShowDetails"
android:text="load data"
android:textAlignment="center"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<TextView
android:id="@+id/res"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:clickable="false"
android:ems="10"
android:textColor="@android:color/holo_green_dark"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
Java File
package com.example.ifcdiv;
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
}
public void onClickShowDetails(View view) {
if(cursor.moveToFirst()) {
StringBuilder strBuild=new StringBuilder();
while (!cursor.isAfterLast()) {
strBuild.append("\n"+cursor.getString(cursor.getColumnIndex("id"))+ "-"+
cursor.getString(cursor.getColumnIndex("name")));
cursor.moveToNext();
}
resultView.setText(strBuild);
}
else {
resultView.setText("No Records Found");
}
}
}
AsyncTask
Android AsyncTask is an abstract category provided by android which provides the freedom to
perform significant tasks within the background and keep the UI thread lightweight thus making
the application more responsive.
Android AsyncTask to perform the significant tasks in background on a dedicated thread and
passing the results back to the UI thread.
Use of AsyncTask in android application keeps the UI thread responsive at all times.
Android AsyncTask going to do background operation on background thread and update on main
thread.
In android we cant directly touch background thread to main thread in android development.
asynctask help us to make communication between background thread to main thread.
Methods of AsyncTask