MAD Unit-5
MAD Unit-5
Activities
1
An activity is a class that represents a single screen. It is like a Frame in
AWT.
Services
2
They handle background processing associated with an application.
Broadcast Receivers
3
They handle communication between Android OS and applications.
Content Providers
4
They handle data and database management issues.
1.Activities
An activity represents a single screen with a user interface,in-short Activity performs
actions on the screen. For example, an email application might have one activity that
shows a list of new emails, another activity to compose an email, and another activity
for reading emails. If an application has more than one activity, then one of them should
be marked as the activity that is presented when the application is launched.
An activity is implemented as a subclass of Activity class as follows −
public class MainActivity extends Activity {
}
2.Services
A service is a component that runs in the background to perform long-running
operations. For example, a service might play music in the background while the user is
in a different application, or it might fetch data over the network without blocking user
interaction with an activity.
A service is implemented as a subclass of Service class as follows −
public class MyService extends Service {
}
3.Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or
from the system. For example, applications can also initiate broadcasts to let other
applications know that some data has been downloaded to the device and is available
for them to use, so this is broadcast receiver who will intercept this communication and
will initiate appropriate action.
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each
message is broadcaster as an Intent object.
public class MyReceiver extends BroadcastReceiver {
public void onReceive(context,intent){}
}
4.Content Providers
A content provider component supplies data from one application to others on request.
Such requests are handled by the methods of the ContentResolver class. The data may
be stored in the file system, the database or somewhere else entirely.
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.
public class MyContentProvider extends ContentProvider {
public void onCreate(){}
}
5.1 Intent
Android Intent is the message that is passed between components such as activities,
content providers, broadcast receivers, services etc.
Intents are used generally for starting a new activity using startActivity().
Component Description
Types of Intents:
Implicit Intent doesn’t specify the component. In such a case, intent provides
information on available components provided by the system that is to be invoked.
Example-
You may write the following code to view the webpage.
If you observe above implicit intent we didn’t defined any specific name of component
to start, instead we defined an action (ACTION_VIEW) to open the defined URL
(http://www.tutlane.com) in browser within the device.
Following is the simple code snippet of implicit intent in the android application.
activity_main.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Implicit Intent Example"
android:id="@+id/implicit_Intent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.EditText;
implicit_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
}
2. xplicit Intent:
Click on Explicit Intent Example. The SecondActivity will be open within the App:
Step 1: Let’s design the UI of activity_main.xml
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
tools:context=".MainActivity"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Explicit Intent Example"
android:id="@+id/explicit_Intent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="147dp" />
</RelativeLayout>
Step 2: Design the UI of second activity activity_second.xml
activity_second.xml
android:layout_height="match_parent"
android:background="#CCEEAA"
tools:context=".SecondActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="This is Second Activity"
android:id="@+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.content.Intent;
import android.view.View;
Button explicit_btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
explicit_btn = (Button)findViewById(R.id.explicit_Intent);
explicit_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
Step 4: Create A New JAVA class name SecondActivity
Now we need to create another SecondActivity.java which will simply open the
layout of activity_second.xml . Also we will use Toast to display message that he is
on second activity.
SecondActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</activity>
</application>
</manifest>
Intent Filter are the components which decide the behavior of an intent. As we have
know Intent about the navigation of one activity to another, that can be achieve by
declaring intent filter. We can declare an Intent Filter for an Activity in manifest file.
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 (i.e. activity,
services or broadcast receiver). It declares the capability of any activity or services or a
broadcast receiver.
● Implicit intent uses the intent filter to serve the user request.
● The intent filter specifies the types of intents that an activity, service, or
broadcast receiver can respond.
● Intent filters are declared in the Android manifest file.
● Intent filter must contain <action>
<activity android:name=".MainActivity">
<intent-filter android:icon="@drawable/icon"
android:label="@string/label"
>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
icon: This is displayed as icon for activity. You can check or save png image of
name icon in drawable folder. If icon image of any other name is stored please
replace @drawable/icon with that image name i.e. @drawable/image_name.
label: The label / title that appears at top in Toolbar of that particular Activity.
You can check or edit label name by opening String XML file present inside Values
folder (Values -> Strings). Replace @string/label to @string/yourlabel.
Elements In Intent Filter:
There are following three elements in an intent filter:
1. Action
2. Data
3. Category
Important Note: Every intent filter must contain action element in it. Data
and category element is optional for it.
1.<action>
A string that specifies the generic action to perform (such as view or pick).
It represent an activities action, what an activity is going to do. It is declared with the
name attribute as given below
<action android:name = "string" />
An Intent Filter element must contain one or more action element. Action is a string that
specifies the action to perform. You can declare your own action as given below. But we
usually use action constants defined by Intent class.
<intent-filter>
<action android:name="com.example.android.intentfilters.Main2Activity"/>
</intent-filter>
ACTION_VIEW
Use this action in an intent with startActivity() when you have some information
that an activity can show to the user, such as a photo to view in a gallery app, or
an address to view in a map app.
ACTION_SEND
Also known as the share intent, you should use this in an intent
with startActivity() when you have some data that the user can share through
another app, such as an email app or social sharing app.
2.<category>
It defines the name of an intent category to be accepted and it must be the literal string
value of an action, not the class constant.
CATEGORY_BROWSABLE
Browsable category, activity allows itself to be opened with web browser to open the
reference link provided in data.
The target activity allows itself to be started by a web browser to display data
referenced by a link, such as an image or an e-mail message.
CATEGORY_LAUNCHER
The activity is the initial activity of a task and is listed in the system's application
launcher. Launcher category puts an activity on the top of stack, whenever application
will start, the activity containing this category will be opened first.
3.<data>
It defines the type of data to be accepted and by using one or more attributes we can
specify various aspects of the data URI (scheme, host, port, path) and MIME type.
Declares the type of data accepted, using one or more attributes that specify various
aspects of the data URI (scheme, host, port, path) and MIME type.
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
If you observe above code snippet the activity “MainActivity” will act as an entry point
for our app because we defined an activity using MAIN action
and LAUNCHER category attributes in intent filters (<intent-filter>).
MAIN - It indicates the app’s main entry point that means it starts the activity which
defines with the MAIN action when the user initially launches the app with a launcher
icon.
LAUNCHER - It indicates that this activity icon should be placed on the home screen
list of apps. In case if the <activity> element doesn’t specify an icon with icon, then the
system uses the icon from the <application> element.
These two (MAIN, LAUNCHER) elements must be paired together in order for the
activity to appear in the app launcher.
In android, Implicit Intents won’t specify any name of the component to start instead, it
declare an action to perform and it allows a component from other apps to handle it. For
example, by using implicit intents we can request another app to show the location
details of the user or etc.
Following is the pictorial representation of how Implicit intents send a request to the
android system to start another activity.
If you observe the above image Activity A creates an intent with the required action
and sends it to an android system using the startActivity() method. The android system
will search for an intent filter that matches the intent in all apps. Whenever the match
found the system starts matching activity (Activity B) by invoking
the onCreate() method.
In android when we create implicit intents, the android system will search for matching
components by comparing the contents of intent with intent filters which defined in
the manifest file of other apps on the device. If the matching component found, the
system starts that component and sends it to the Intent object. In case, if multiple intent
filters are matched then the system displays a dialog so that the user can pick which app
to use.
In android, an Intent Filter is an expression in the app’s manifest file and it is used to
specify the type of intents that the component would like to receive. In case if we create
an Intent Filter for activity, there is a possibility for other apps to start our activity by
sending a certain type of intent otherwise the activity can be started only by an explicit
intent.
Intents with Parameters
● The name to identify and retrieve the value later (String type)
● The value you want to send, identified by the name you define as the first
argument (Any valid type)
For example, suppose you want to send a Hello World! string from MainActivity to
SecondActivity. This is how you do it:
// In MainActivity class
Intent secondActivityIntent = new Intent(this, SecondActivity.class);
startActivity(secondActivityIntent);
First, you create a new Intent object. Then, you call the putExtra() method from that
object.
The first argument is the name of the extra, which is message in the example above.
In the SecondActivity class, you can retrieve the extra using the getStringExtra()
method:
String msg = getIntent().getStringExtra("message");
The msg variable above will contain the Hello World! string saved under the message
name identifier.
Android has many get__Extra() methods, and each is used to retrieve an extra of a
specific type through the Intent object.
If you send a boolean value, you need to retrieve it using getBooleanExtra().
For an int value, you need to use the getIntExtra(), and so on.
Sending a serializable object as an extra
Sending many values using an Intent object is a bit tedious because you need to
repeatedly call the putExtra() method for each value.
The example below shows how you send three values using the Intent object:
secondActivityIntent.putExtra("username", "Nathan");
secondActivityIntent.putExtra("age", 23);
secondActivityIntent.putExtra("isLegal", true);
Instead of sending the extras one by one, you can create a Serializable class that you can
use to store your data in one object.
First, create a class that implements the Serializable interface. For our example, let’s
name it Profile:
class Profile implements Serializable {
String username;
int age;
boolean isLegal;
In your MainActivity class, create a new Profile object with the data you want to send
to the SecondActivity.
Send the Profile object as an extra with the putExtra() method:
// In MainActivity class
startActivity(secondActivityIntent);
Next, you need to get the profile extra from the SecondActivity class.
Use the getSerializableExtra() method to get the object, then cast the object as the
Profile class type:
// In SecondActivity class
Serializable s = getIntent().getSerializableExtra("profile");
Profile p = (Profile) s;
1. Action:
There are few common actions for starting an activity like ACTION_VIEW
2. Data:
There are two forms in which you can pass the data, using URI(Uniform Resource
Identifiers) or MIME type of data. For understanding the concept of URI in better
manner check the link.
1. Write a program to create two screens. First screen will take two number
asinput from user .Addition of two numbers in one activity and sending
Result to another activity to display the result.
2. Write a program to create two screens. First screen will take one number
input from user. After click on Factorial button, second screen will open
and it should display factorial of the same number. Also specify which
type of intent you will use in this case.
Step 2-result.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/resultView"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"/>
</LinearLayout>
Step 3-MainActivity.java
package com.tutlane.intents;
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText firstNum = (EditText)findViewById(R.id.firstNum);
final EditText secNum = (EditText)findViewById(R.id.secondNum);
Button btnAdd = (Button)findViewById(R.id.addBtn);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num1 = Integer.parseInt(firstNum.getText().toString());
int num2 = Integer.parseInt(secNum.getText().toString());
Intent intent = new Intent(MainActivity.this,ResultActivity.class);
intent.putExtra("SUM",num1+" + "+num2+" = "+(num1+num2));
startActivity(intent);
}
});
}
}
Step 4-ResultActivity.java
package com.tutlane.intents;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
/**
* Created by surdasari on 27-07-2017.
*/
1. OnCreate()
2. OnStart()
3. OnResume()
4. OnPause()
5. OnStop()
6. OnRestart()
7. OnDestroy()
Activity Description
Methods
OnCreate() This method is called when activity is created. It is used to
initialize the activity.
States of an Activity
Activity Description
State
Running This state defines that the activity is visible and interacts with the
user.
Paused This state defines that the activity is still visible but partially hidden
and the instance is running but might be killed by the system.
Stopped This state defines that the activity is not visible and the instance is
running but might be killed by the system.
Killed This state defines that the activity has been terminated by the system
call to its finish() method.
It provides the details about the invocation of life cycle methods of activity. In this
example, we are displaying the content on the logcat.
File: MainActivity.java
1. package example.javatpoint.com.activitylifecycle;
2.
3. import android.app.Activity;
4. import android.os.Bundle;
5. import android.util.Log;
6.
7. public class MainActivity extends Activity {
8.
9. @Override
10. protected void onCreate(Bundle savedInstanceState) {
11. super.onCreate(savedInstanceState);
12. setContentView(R.layout.activity_main);
13. Log.d("lifecycle","onCreate invoked");
14. }
15. @Override
16. protected void onStart() {
17. super.onStart();
18. Log.d("lifecycle","onStart invoked");
19. }
20. @Override
21. protected void onResume() {
22. super.onResume();
23. Log.d("lifecycle","onResume invoked");
24. }
25. @Override
26. protected void onPause() {
27. super.onPause();
28. Log.d("lifecycle","onPause invoked");
29. }
30. @Override
31. protected void onStop() {
32. super.onStop();
33. Log.d("lifecycle","onStop invoked");
34. }
35. @Override
36. protected void onRestart() {
37. super.onRestart();
38. Log.d("lifecycle","onRestart invoked");
39. }
40. @Override
41. protected void onDestroy() {
42. super.onDestroy();
43. Log.d("lifecycle","onDestroy invoked");
44. }
45.}
Output:
You will not see any output on the emulator or device. You need to open logcat.
Example-Summer 22
Write a program to implement Android Activity Life Cycle. Use toast messages to
display message through life cycle. (Note: No XML code is required. In java file all
imports are not expected.)6 MARKS
Use Toast class instead of Log.d in above example
Broadcast intents
1. Ordered Broadcasts
2. Normal Broadcasts
1.Ordered Broadcasts
This method sends broadcasts to one receiver at a time, Ordered Broadcast is the type
of broadcast which is sent in a synchronous manner i.e. one by one to each listener.
Ordered Broadcast method falls in the Context class of Android, the purpose of this
method is to broadcast to listening receivers in a serialised manner and receive the result
back to the calling activity. Another key advantage of sendOrderedBroadcast is that
we can set the priority of BroadcastReceiver. This way all
the BroadcastReceivers listening to that specific broadcast will receive that specific
broadcast in an ordered manner.
2. Normal Broadcasts
Normal broadcasts are asynchronous and unordered. These receivers run unorderly or
all at a time, sometimes. In normal broadcast, it’s possible that the system sends only
one broadcast at a time in order to avoid overhead. It can also abort the broadcast, but
those excluding APIs.
Notification that we receive from the applications can also be muted.
A broadcast intent could be received by multiple receivers while other intents will be
caught by a specific activity
Generally, we use Intents to deliver broadcast events to other apps and Broadcast
Receivers use status bar notifications to let the user know that broadcast event occurs.
A. System-generated Intents
B. Broadcasting Custom Intents
A. System-generated Intents
Let us see some system-generated Intents which are important and are generally used:
There is one additional steps in case you are going to implement your custom intents
then you will have to create and broadcast those intents.
Receiving Broadcasts
<receiver android:name="SampleBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
The above statement will fire the defined system broadcast event whenever the boot
process is completed.
If you want your application itself should generate and send custom intents then you
will have to create and send those intents by using the sendBroadcast() method inside
your activity class.
In android, we can create our own custom broadcasts using intents. Following is the
simple code snippet of sending a broadcast by creating an intent using
sendBroadcast(Intent) method.
<intent-filter>
<action android:name=" com.example.myapplication.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
Sending Broadcasts
In android, we can send a broadcasts in apps using three different ways, those are
Method Description
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example of Broadcast"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="Broadcast Intent"
android:onClick="broadcastIntent"
android:layout_below="@+id/imageButton"
android:layout_centerHorizontal="true" />
</RelativeLayout>
MainActivity.java
package com.example.tutorialspoint7.myapplication;
import android.app.Activity;
int
public class MainActivity extends Activity {
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name=" com.example.myapplication.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
</application>
</manifest>
https://protocoderspoint.com/how-to-check-internet-connection-in-android/
In Android, Content Providers are a very important component that serves the purpose
of a relational database to store the data of applications. The role of the content provider
in the android system is like a central repository in which data of the applications are
stored, and it facilitates other applications to securely access and modifies that data
based on the user requirements. Android system allows the content provider to store the
application data in several ways. Users can manage to store the application data like
images, audio, videos, and personal contact information by storing them in SQLite
Database, in files, or even on a network. In order to share the data, content providers
have certain permissions that are used to grant or restrict the rights to other applications
to interfere with the data.
Content URIs
The content resolver provides access to your content provider. As the name suggests, a
content resolver accepts requests from clients and resolves them by directing them to a
content provider with a distinct authority. The mapping from authorities to content
providers is stored by the content resolver. This design is a necessity for simple and
secure means of accessing the content providers of other applications. For different
abstract methods like insert, query, update, and delete, content resolver uses CRUD
In android, Content URI is a URI that is used to query a content provider to get the
required data. The Content URIs will contain the name of an entire-provider
(authority) and the name that points to a table (path).
Generally the format of URI in android applications will be like as shown below
content://authority/path
Following are the details about various parts of an URI in android application.
content:// - The string content:// is always present in the URI and it is used to represent
the given URI is a content URI.
authority - It represents the name of content provider, for example phone, contacts, etc.
and we need to use a fully qualified name for third party content providers like
com.tutlane.contactprovider
content://contacts_info/users
Here the string content:// is used to represent URI is a content URI, contacts_info
string is the name of the provider’s authority and users string is the table’s path.
update() An existing row's fields can be updated using this technique. The
amount of updated rows is returned.
delete() The current rows may be deleted using this technique. The amount
of removed rows is returned.
getType() Data of the Multipurpose Internet Mail Extension (MIME) type are
returned by this function to the specified Content URI.
onCreate() The Android system invokes this method to initialize the content
provider as soon as it is established.
CRUD Operations
Content providers provide the following four basic operations. These are also known as
CRUD operations, where
C – Create
R – Read
U – Update
D – Delete
The above are the four operations of content providers :
Following are the six abstract methods and their description which are essential to
override as the part of ContenProvider class:
Abstract
Description
Method
A method that accepts arguments and fetches the data from the
query()
desired table. Data is retired as a cursor object.
Android Fragments
Following is the example of defining a multiple fragments in single activity for the
tablet design to display the details of an item which we selected in the app, but
separated for mobile design
If you observe above example for Tablet we defined an Activity A with two fragments
such as one is to show the list of items and second one is to show the details of item
which we selected in first fragment.
For Handset device, there is no enough space to show both the fragments in single
activity, so the Activity A includes first fragment to show the list of items and the
Activity B which includes another fragment to display the details of an item which is
selected in Activity A.
For example, GMAIL app is designed with multiple fragments, so the design of
GMAIL app will be varied based on the size of device such as tablet or mobile device.
Table View
Mobile View
Basic Fragment Code In XML:
<fragment
android:id="@+id/fragments"
android:layout_width="match_parent"
android:layout_height="match_parent" />
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
In this case we’ll pass false because the View will be attached to the parent ViewGroup
elsewhere, by some of the Android code we call. When you pass false as last parameter
to inflate(), the parent ViewGroup is still used for layout calculations of the inflated
View, so you cannot pass null as parent ViewGroup . ViewGroup parameter of
onCreateView() is the parent ViewGroup into which the View of the fragment is to be
inserted. This is a ViewGroup inside the activity that will “host” the
fragment. Bundle parameter of onCreateView() is a Bundle in which the fragment can
save data, just like in an Activity
FRAGMENT LIFECYCLE
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.
Android fragment lifecycle is affected by activity lifecycle because fragments are
included in activity.
Each fragment has its own life cycle methods that is affected by activity life cycle
because fragments are embedded in activity.
The FragmentManager class is responsible to make interaction between fragment
objects.
Following are the list of methods which will perform during the lifecycle of fragment in
android applications.
Types of Fragments
Basically fragments are divided as three stages as shown below.
1.Single frame fragments − Single frame fragments are using for hand hold devices
like mobiles, here we can show only one fragment as a view.
2.List fragments − fragments having special list view is called as list fragment
The basic implementation of list fragment is for creating list of items in fragments
List in Fragments
<fragment
android:id="@+id/fragment1"
android:name="com.example.myapplication.Fragment1"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
/>
<fragment
android:id="@+id/fragment2"
android:name="com.example.myapplication.Fragment2"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</LinearLayout>
File: fragment_fragment1.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="#F5F5DC"
tools:context=".Fragment1">
</FrameLayout>
File: fragment_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="#F0FFFF"
tools:context=".Fragment2">
</FrameLayout>
File: MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
File: Fragment1.java
package com.example.myapplication;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
import androidx.appcompat.app.AppCompatActivity;
public class Fragment1 extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}
File: Fragment2.java
package com.example.myapplication;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment2, container, false);
}
When we talk about services, they can be of three types as shown in the figure below:
1. Foreground Services
Services that notify the user about its ongoing operations are termed as Foreground
Services. Users can interact with the service by the notifications provided about the
ongoing task. Such as in downloading a file, the user can keep track of the progress in
downloading and can also pause and resume the process.
1. Background Services
Background services do not require any user intervention. These services do not notify
the user about ongoing background tasks and users also cannot access them. The
process like schedule syncing of data or storing of data fall under this service.
2. Bound Services
This type of android service allows the components of the application like activity
to bound themselves with it. Bound services perform their task as long as any
application component is bound to it. More than one component is allowed to bind
themselves with a service at a time. In order to bind an application component
with a service bindService() method is used.
1. Started
2. Bound
1) Started Service
By following this path, a service will initiate when an application component calls
the startService() method. Once initiated, the service can run continuously in the
background even if the component is destroyed which was responsible for the start of
the service. Two option are available to stop the execution of service:
● By calling stopService() method,
● The service can stop itself by using stopSelf() method.
2) Bound Service
The Android system invokes this method when all the clients
onUnbind()
get disconnected from a particular service interface.
a one-time-set-up.
You must declare all services in your application's manifest file, just as you do for
activities and other components.
To declare your service, add a <service> element as a child of the <application>
element. Here is an example:
<manifest ... >
...
<application ... >
<service android:name=".ExampleService" />
...
</application>
</manifest>
Ste Description
p
1 You will use Android StudioIDE to create an Android application and name it
as My Application under a package com.example..myapplication
7 Run the application to launch Android emulator and verify the result of the
changes done in the application.
To create a service, we need to create a class that extends a Service base class or one of
its existing subclasses. During our service implementation, we must need to override
some of the callback methods that handle the key aspects of the service lifecycle and
provide the functionality that allows our components to bind to the service.
Create a Service
Generally, in android to create a service we must create a subclass of Service or use one
of existing subclass. In android the application component such as an activity can start
the service by calling startService() which results in calling the service’s
onStartCommand() method.
Following is the simple example of creating a service in android application.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO write your own code
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
Once we create a service, we need to register that in android manifest file using
<service> element like as shown below.
In android, the component such as an activity, service or receiver can start the service
using startService() method. Following is the sample code snippet of starting a service
using the startService method.
need to continue running in the background even if the user switches to another app or
device. By using START_STICKY you can ensure that your service continues to run
Example1:
Step 1)Activity_main.xml
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example of services"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:text="Start Services"
android:onClick="startService"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Services"
android:id="@+id/button"
android:onClick="stopService"
android:layout_below="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2"
android:layout_alignRight="@+id/button2"
android:layout_alignEnd="@+id/button2" />
</RelativeLayout>
Step 2)MainActivity.java
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
String msg = "Android : ";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(msg, "The onCreate() event");
}
{
Intent intent = new Intent(this, MyService.class);
startService(inten);
}
Step 3-MyService.java
package com.example.myapplication;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.Nullable;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</manifest>
Example2:
Following is the example of start playing music in the background when we start a
service and that music will play continuously until we stop the service in the android
application.
Create a new android application using android studio and give names as Services. In
case if you are not aware of creating an app in android studio check this article Android
Hello World App.
Once we create a new file MyService.java, open it and write the code like as shown
below
Output of Android Service Example
When we run above example in android emulator we will get a result like as shown
below
If we click on Start Service button, the default ringtone will start playing and it will
continue until we stop the service. This is how we can create, start or stop services in
android applications based on our requirements.
If we click on Start Service button, the default ringtone will start playing and it will
continue until we stop the service. This is how we can create, start or stop services in
android applications based on our requirements.
package com.tutlane.services;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;
Now open activity_main.xml file from \src\main\res\layout path and write the following
code.
Step 1)Activity_main.xml
ut>
Now open MainActivity.java file from \java\com.tutlane.services path and write
following to implement custom broadcast intents.
Step 2)MainActivity.java
package com.tutlane.services;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// Start the service
public void startService(View view) {
startService(new Intent(this, MyService.class));
}
// Stop the service
public void stopService(View view) {
stopService(new Intent(this, MyService.class));
}
}
Step 3) MyService.java
<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/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService" />
</application>
</manifest>
Permissions in android
When building an Android application, we require different Android device
components such as the camera, GPS, and so on. So, in order to use these capabilities of
our Android smartphone, we must first obtain permission from the user to use
something on their phone. You cannot utilize any of those functionalities directly.
Furthermore, permission has different protection levels; for example, if the permission’s
protection level is very low, you do not need to ask the user to use that permission. You
may use it right away. However, for hazardous permissions, you must expressly obtain
the user’s permission. In this geeks for geeks article, we will learn about the various
layers of authorization protection.
Android permissions provide controls that increase user awareness and limit an app’s
access to sensitive data.
Steps for Requesting permissions at run time
Declare the permission in the Android Manifest file:
In Android, permissions are declared in the AndroidManifest.xml file using
the uses-permission tag.
<uses-permission android:name=”android.permission.PERMISSION_NAME”/>
The three permission protection levels in Android are as follows
1. Normal Permissions
2. Signature Permissions
3. Dangerous Permissions
These are the three primary permissions protection levels; however, there is an
additional security level known as the Special Permission. Let’s take a look at them one
at a time.
Permission Category #1: Normal Permissions
The permission falls within the Normal Permission category if there is little or no
danger to the user’s privacy. For example, if you want to acquire the data and time,
these things do not entail any user privacy, and you do not need to ask the user to use
date or time in this situation. You may utilize this feature directly by adding permission
to the AndroidManifest.xml file. The system will automatically provide authorization to
your app during the installation process. Normal Permissions include the following
permissions:
1. ACCESS_LOCATION_EXTRA_COMMANDS
2. ACCESS_NETWORK_STATE
3. CHANGE_NETWORK_STATE
4. ACCESS_WIFI_STATE
5. CHANGE_WIFI_STATE
6. CHANGE_WIFI_MULTICAST_STATE
7. BLUETOOTH
8. BLUETOOTH_ADMIN
9. INTERNET
10.SET_ALARM
11.SET_WALLPAPER
12.VIBRATE
13.WAKE_LOCK
Permission Category #2: Signature Authorization
The Android system gives these rights during installation, but there is a catch. The app
requesting permission must be signed with the same signature as the app defining the
needed permission. Some of the Signature permissions are as follows:
1. BIND_ACCESSIBILITY_SERVICE
2. BIND_AUTOFILL_SERVICE
3. BIND_CARRIER_SERVICE
4. BIND_DEVICE_ADMIN
5. BIND_INPUT_METHOD
6. BIND_NFC_SERVICE
7. BIND_TV_INPUT
8. BIND_WALLPAPER
9. READ_VOICEMAIL
10.WRITE_SETTINGS
11.WRITE_VOICEMAIL
Permission Category #3: The dangerous ones
Permissions that are dangerous include those that affect user data in some way. For
example, if you wish to read contacts from the phone or access the phone’s file storage,
these rights fall under the Dangerous category since they involve the user’s privacy. To
utilize Dangerous permissions, you must first expressly seek permission by displaying
an alert dialogue or any other dialogue. If the user refuses the permission, your
application will be unable to utilize that permission. Some of the Dangerous
permissions are as follows:
1. READ_CALENDAR
2. WRITE_CALENDAR
3. CAMERA
4. READ_CALL_LOG
5. WRITE_CALL_LOG
6. READ_CONTACTS
7. WRITE_CONTACTS
8. GET_ACCOUNTS
9. ACCESS_FINE_LOCATION
10.ACCESS_COARSE_LOCATION
11.SEND_SMS
12.RECEIVE_SMS
By using WifiManager class, we can perform the operations that are related to network
connectivity. We can instantiate this class by using Context.getSystemService(Class)
with the argument WifiManager.class or Context.getSystemService(String) with the
argument Context.WIFI_SERVICE.
WifiManager wmgr =
(WifiManager)Context.getSystemService(Context.WIFI_SERVICE);
If you observe above code snippet, we used getSystemService() method to instantiate a
WifiManager class.
In case if getSystemService() method returns NULL, then the device does not support
Wi-Fi and we can disable all Wi-Fi features.
Android Enable or Disable Wi-Fi
If Wi-Fi is supported but disabled, then isWifiEnabled() method will return false and
we can request user to enable wifi without leaving our application by using
setWifiEnabled method.
WifiManager wmgr =
(WifiManager)Context.getSystemService(Context.WIFI_SERVICE);
wmgr.setWifiEnabled(true);
If you observe above code snippet, we used setWifiEnabled(true) method to turn ON
or Enable a Wi-Fi in our android application.
Create a new android application using android studio and give names as WifiExample.
In case if you are not aware of creating an app in android studio check this article
Android Hello World App.
MainActivity.java
package com.tutlane.wifiexample;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
When we run the above program in the android studio we will get the result as shown
below.
When we click on Turn ON button, the device Wi-Fi gets switched ON and when we
click on Turn OFF button, the device Wi-Fi get switched OFF.
This is how we can turn ON or OFF Wi-Fi in android applications based on our
requirements.
Example 2: Bluetooth connectivity
Bluetooth is a way to send or receive data between two different devices. Android
platform includes support for the Bluetooth framework that allows a device to
wirelessly exchange data with other Bluetooth devices.
Android provides Bluetooth API to perform several tasks such as:
scan bluetooth devices
connect and transfer data from and to other devices
manage multiple connections etc.
o String ACTION_REQUEST_ENABLE
o String ACTION_REQUEST_DISCOVERABLE
o String ACTION_DISCOVERY_STARTED
o String ACTION_DISCOVERY_FINISHED
Once you enable the Bluetooth , you can get a list of paired devices by calling
getBondedDevices() method. It returns a set of bluetooth devices. Its syntax is.
private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();
Following is the code snippet to disable or turn off Bluetooth in android applications
using disable() function.
icon from the tool bar.If your Bluetooth will not be turned on then, it will ask your
permission to enable the Bluetooth.
Now just select the Get Visible button to turn on your visibility. The following screen
would appear asking your permission to turn on discovery for 120 seconds.
Now just select the List Devices option. It will list down the paired devices in the list
view. In this example is shows only one paired device. It is shown below.
Now just select the Turn off button to switch off the Bluetooth. Following message
would appear when you switch off the bluetooth indicating the successful switching off
of Bluetooth.
When we click on Turn ON button, the device Bluetooth gets switched ON and when
we click on Turn OFF button, the device Bluetooth gets switched OFF.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_toStartOf="@+id/imageView"
android:layout_toLeftOf="@+id/imageView"
android:clickable="true"
android:onClick="on" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get visible"
android:onClick="visible"
android:id="@+id/button2"
android:layout_alignBottom="@+id/button"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List devices"
android:onClick="list"
android:id="@+id/button3"
android:layout_below="@+id/imageView"
android:layout_toRightOf="@+id/imageView"
android:layout_toEndOf="@+id/imageView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="turn off"
android:onClick="off"
android:id="@+id/button4"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_below="@+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paired devices:"
android:id="@+id/textView2"
android:textColor="#ff34ff06"
android:textSize="25dp"
android:layout_below="@+id/button4"
android:layout_alignLeft="@+id/listView"
android:layout_alignStart="@+id/listView" />
</RelativeLayout>
MainActivity.java
package com.example.myapplication;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button3);
b4=(Button)findViewById(R.id.button4);
BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.listView);
}
lv.setAdapter(adapter);
}
}
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Async Task
AsyncTask is defined by three generic types. These are called Params, Progress, and
Result.
AsyncTask <TypeOfVarArgParams, ProgressValue, ResultValue>
3. Result → The result which is obtained after the background thread has
finished execution.
The following code snippet must be present in the MainActivity class in order to launch
an AsyncTask.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ExampleAsync task = new ExampleAsync;
task.execute(10);
}
@Override
protected String doInBackground(Integer... integers) {
// ...
return "Finished!";
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// ...
}
@Override
protected void onPostExecute(String string) {
super.onPostExecute(string);
// ...
}
}
}
AsyncTask Flow
\
AsyncTask has four methods that are called onPreExecute, doInBackground,
onProgressUpdate and onPostExecute.
1.onPreExecute() - This part of the method gets executed on the main thread. Before
doing a background operation you should show something on-screen like a progress bar
doInBackground method and runs on the UI thread. This method is used to display
operation result.
Example 1-
In this example AsyncTaskRunner class to perform the AsyncTask operations. The time
in seconds is passed as a parameter to the class and a ProgressDialog is displayed for
the given amount of time. The images given below are the outputs produced by the
project where the time set by the user is 5 seconds.
Android AsyncTask Example Code
<TextView
android:id="@+id/tv_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10pt"
android:textColor="#444444"
android:layout_alignParentLeft="true"
android:layout_marginRight="9dip"
android:layout_marginTop="20dip"
android:layout_marginLeft="10dip"
android:text="Sleep time in Seconds:"/>
<EditText
android:id="@+id/in_time"
android:layout_width="150dip"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"
android:layout_toRightOf="@id/tv_time"
android:layout_alignTop="@id/tv_time"
android:inputType="number"
/>
<Button
android:id="@+id/btn_run"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Run Async task"
android:layout_below="@+id/in_time"
android:layout_centerHorizontal="true"
android:layout_marginTop="64dp" />
<TextView
android:id="@+id/tv_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="7pt"
android:layout_below="@+id/btn_run"
android:layout_centerHorizontal="true" />
</RelativeLayout>
In the above layout we’ve used a predefined drawable as the border of the EditText. The
MainActivity.java is defined below:
package com.journaldev.asynctask;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"ProgressDialog",
"Wait for "+time.getText().toString()+ " seconds");
}
@Override
protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
int time = Integer.parseInt(params[0])*1000;
Thread.sleep(time);
resp = "Slept for " + params[0] + " seconds";
} catch (InterruptedException e) {
e.printStackTrace();
resp = e.getMessage();
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
@Override
protected void onProgressUpdate(String... text) {
finalResult.setText(text[0]);
@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
progressDialog.dismiss();
finalResult.setText(result);
}
}
}
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all
required details to create a new project.
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = (EditText) findViewById(R.id.in_time);
button = (Button) findViewById(R.id.btn_run);
finalResult = (TextView) findViewById(R.id.tv_result);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AsyncTaskRunner runner = new AsyncTaskRunner();
String sleepTime = time.getText().toString();
runner.execute(sleepTime);
}
});
}
@Override
protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
int time = Integer.parseInt(params[0])*1000;
Thread.sleep(time);
resp = "Slept for " + params[0] + " seconds";
} catch (InterruptedException e) {
e.printStackTrace();
resp = e.getMessage();
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
progressDialog.dismiss();
finalResult.setText(result);
}
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"ProgressDialog",
"Wait for "+time.getText().toString()+ " seconds");
}
@Override
protected void onProgressUpdate(String... text) {
finalResult.setText(text[0]);
}
}
}
2) Native Libraries
On the top of linux kernel, their are Native libraries such as WebKit, OpenGL,
FreeType, SQLite, Media, C runtime library (libc) etc.
3) Android Runtime
In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is
responsible to run android application. DVM is like JVM but it is optimized for mobile
devices. It consumes less memory and provides fast performance.
4) Android Framework
On the top of Native libraries and android runtime, there is android framework. Android
framework includes Android API's such as UI (User Interface), telephony, resources,
locations, Content Providers (data) and package managers. It provides a lot of classes
and interfaces for android application development.
5) Applications
On the top of android framework, there are applications. All applications such as home,
contact, settings, games, browsers are using android framework that uses android
runtime and libraries. Android runtime and native libraries are using linux kernal.
Multimedia framework
Get a result from an activity
Starting another activity, whether it is one within your app or from another app, doesn't
need to be a one-way operation. While the
underlying startActivityForResult() and onActivityResult() APIs are available on
the Activity class on all API levels, Google strongly recommends using the Activity
Result APIs introduced in AndroidX Activity and Fragment classes.
The Activity Result APIs provide components for registering for a result, launching the
result, and handling the result once it is dispatched by the system.
By the help of android startActivityForResult() method, we can get result from another
activity.
The request code is an integer value that the original activity uses to identify the result
from the started activity.
When the started activity finishes, it sets a result using the setResult method and the
original activity receives this result in its onActivityResult method.
The onActivityResult method takes three parameters: the request code, a result code,
and an Intent containing the data returned by the started activity.
Always make sure to check the request code in the onActivityResult method to ensure
that the result is from the correct activity. This can be done by comparing the request
code passed to the StartActivityForResult method with the request code received in
onActivityResult.
MainActivity.java
// Start the SecondActivity
startActivityForResult(intent,SECOND_ACTIVITY_REQUEST_CODE);
@Override
if (requestCode == SECOND_ACTIVITY_REQUEST_CODE)
{
if (resultCode == RESULT_OK)
{ // Activity.RESULT_OK
// get String data from Intent
}
else if (resultCode == RESULT_CANCELED)
{
Toast.makeText(this, "Cancelled",Toast.LENGTH_LONG).show();
}
}
Image Capture
Program1.Write a program to capture an image and display it using image view.
Camera is mainly used to capture picture and video. We can control the camera by
using methods of camera api.
Android provides the facility to work on camera by 2 ways:
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
● Camera
It is main class of camera api, that can be used to take picture and video.
● SurfaceView
It represents a surface view ore preview of live camera.
● MediaRecorder
It is used to record video using camera. It can also be used to record audio files as we
have seen in the previous example of media framework.
In this example, we are writing the simple code to capture image using camera and
displaying the image using imageview.
The opening of the Camera from inside our app is achieved with the help of the
ACTION_IMAGE_CAPTURE Intent of MediaStore class.
This image shows the Image clicked by the camera and set in Imageview. When the app
is opened, it displays the “Camera” Button to open the camera. When pressed,
ACTION_IMAGE_CAPTURE Intent gets started by the MediaStore class. When the
image is captured, it is displayed in the image view.
ACTION_IMAGE_CAPTURE Intent-
This Intent will help to open the camera for capturing the image. Start the intent with
the requested Image_Capture_Code.
startActivityForResult(camera_intent, Image_Capture_Code);
Now use the onActivityResult() method to get the result, here is the captured image.
// Start the activity with camera_intent, and request Image_Capture_Code
startActivityForResult(camera_intent, Image_Capture_Code);
Then set the image received as a result of Camera intent in the ImageView for display.
BitMap is data structure of image file which store the image in memory
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
<ImageView
android:id="@+id/im1"
android:layout_width="410dp"
android:layout_height="410dp"
/>
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Capture and Set Image"
android:textSize="25dp"
android:layout_gravity="center"
android:layout_marginTop="30dp"
/>
</LinearLayout>
MainActivity.java
package com.example.audio_cap;
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;
public class MainActivity extends AppCompatActivity {
private static final int Image_Capture_Code= 1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button) findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View v) {
Intent i1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i1, Image_Capture_Code);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
https://www.techotopia.com/index.php/Video_Recording_and_Image_Capture_using_C
amera_Intents_-_An_Android_Studio_Example#Calling_the_Image_Capture_Intent
Many Android devices are equipped with at least one camera. There are a number of
ways to allow the user to record video from within an Android application via these
built-in cameras, but by far the easiest approach is to make use of a camera intent
included with the Android operating system. This allows an application to invoke the
standard Android video recording interface. When the user has finished recording, the
intent will return to the application, passing through a reference to the media file
containing the recorded video.
The presence of a camera facing away from the device screen can be similarly verified
using the PackageManager.FEATURE_CAMERA constant. A test for whether a device
has any camera can be performed by referencing
PackageManager.FEATURE_CAMERA_ANY.
intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
startActivityForResult(intent, VIDEO_CAPTURE);
When the user either completes or cancels the video recording session, the
onActivityResult() method of the calling activity will be called. This method needs to
check that the request code passed through as an argument matches that specified when
the intent was launched, verify that the recording session was successful and extract the
path of the video media file. The corresponding onActivityResult() method for the
above intent launch code might, therefore, be implemented as follows:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VIDEO_CAPTURE) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Video saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Video recording cancelled.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Failed to record video",
Toast.LENGTH_LONG).show();
}
}
}
Program 2.Write a program to record a video using various camera methods
XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".CameraAppActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/record_string"
android:id="@+id/recordButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="startRecording" />
</RelativeLayout>
Mainactivity.java
package com.example.videocapture;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import android.os.Bundle;
import android.content.pm.PackageManager;
import android.widget.Button;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.content.Intent;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button recordButton =
(Button) findViewById(R.id.recordButton);
if (!hasCamera())
recordButton.setEnabled(false);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, VIDEO_CAPTURE);
}
AndroidManifest.xml
</manifest>
Testing the Application
Compile and run the application on a physical Android device, touch the record button
and use the video capture intent to record some video. Once completed, stop the video
recording. Play back the recording by selecting the play button on the screen. Finally,
touch the Done (sometimes represented by a check mark) button on the screen to return
to the CameraApp application. On returning, a Toast message should appear stating that
the video has been stored in a specific location on the device (the exact location will
differ from one device type to another).
Many apps require the feature to add the audio feature in their application and there so
many audio files that we have to play inside our application. If we will store so many
audio files inside our application, then it will increase the size of the app and this may
reduce the user base due to the huge app size. So the better way to tackle this problem is
to store the audio files in your database and access them from their unique web URL. In
this program, we will take a look at playing an audio file from URL in Android.
In android, by using MediaPlayer class we can easily fetch, decode and play both
audio and video files with minimal setup.
The android media framework provides built-in support for playing a variety of
common media types, such as audio or video.
MediaPlayer class provides a different type of methods to control audio and video files
based on requirements.
Method Description
Method1-
In case, if we want to play an audio from a URI that is locally available in the system, we need to write the
code like as shown below.
If we want to play an audio from a URL via HTTP streaming, we need to write the code like as shown below.
</RelativeLayout>
Adding permissions to the AndroidManifest.xml file
As we are playing audio from URL in android. So we will have to add Internet
permissions to load URL. Add below permissions to the AndroidManifest.xml file
<!-- Permissions of internet -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
/>
MainActivity.java
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pauseBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// checking the media player
// if the audio is playing or not.
if (mediaPlayer.isPlaying()) {
// pausing the media player if media player
// is playing we are calling below line to
// stop our media player.
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
// below line is use to set the audiostream type for our media player.
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (IOException e) {
e.printStackTrace();
}
// below line is use to display a toast message.
Toast.makeText(this, "Audio started playing..", Toast.LENGTH_SHORT).show();
}
}
For showing the video in our android application we will use the VideoView widget.
The VideoView widget is capable of playing media files, and the formats supported by
the VideoView are 3gp and MP4. By using VideoView you can play media files from
the local storage and also from the internet.
Generally, the MediaController class in android will provide playback options for
video player, such as play, pause, backward, forward, etc.
The VideoView class in android will provide the functionality to fetch and play the
videos using video player with minimal setup in android applications.
re we used a Uri object to play videos from our application resource directory
(res/raw). In case if raw folder does not exist in our application, create a
new raw folder under res directory and add properly encoded and formatted video files
in it.
The VideoView class provides a different type of methods to control video files based
on requirements.
Method Description
create a new raw folder in res directory and add one video file like as shown below.
Program 4 : Android Video Player Example
activity_main.xml
MainActivity.java
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
setAudioSource() This method will specify the source of the audio to be recorded.
setOutputFormat() This method is used to specify the output format of our audio.
<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.CamViewLibrary">
<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>
activity_main.xml
</LinearLayout>
</RelativeLayout>
MainActivity.java
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.IOException;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// start recording method will
// start the recording of audio.
startRecording();
}
});
stopTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// pause Recording method will
// pause the recording of audio.
pauseRecording();
}
});
playTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// play audio method will play
// the audio which we have recorded
playAudio();
}
});
stopplayTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// pause play method will
// pause the play of audio
pausePlaying();
}
});
}
startTV.setBackgroundColor(getResources().getColor(R.color.gray));
playTV.setBackgroundColor(getResources().getColor(R.color.gray));
stopplayTV.setBackgroundColor(getResources().getColor(R.color.gray));
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
// this method is called when user will
// grant the permission for audio recording.
switch (requestCode) {
case REQUEST_AUDIO_PERMISSION_CODE:
if (grantResults.length > 0) {
boolean permissionToRecord = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean permissionToStore = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
if (permissionToRecord && permissionToStore) {
Toast.makeText(getApplicationContext(),
"Permission Granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Permission Denied", Toast.LENGTH_LONG).show();
}
}
break;
}
}
startTV.setBackgroundColor(getResources().getColor(R.color.purple_200));
playTV.setBackgroundColor(getResources().getColor(R.color.gray));
stopplayTV.setBackgroundColor(getResources().getColor(R.color.purple_200));
startTV.setBackgroundColor(getResources().getColor(R.color.purple_200));
playTV.setBackgroundColor(getResources().getColor(R.color.purple_200));
stopplayTV.setBackgroundColor(getResources().getColor(R.color.purple_200));
In android, you can convert your text into speech by the help of TextToSpeech class.
After completion of the conversion, you can playback or create the sound file.
It supports different types of speaking languages. We can choose the speaking language
based on our requirements in the android application.
Generally, the android TextToSpeech instance can only be used to synthesize text once
it has completed its initialization so implement TextToSpeech.OnInitListener to notify
the completion of initialization.
During the initialization, we can set the audio pitch rate, audio speed, type of language
to speak, etc. based on our requirements.
Following is the code snippet of converting text to voice using TextToSpeech class in
android applications.
Now we will see how to use the TextToSpeech component to convert the given text to
speech conversion in android application with examples.
activity_main.xml
MainActivity.java
package com.example.myapplication;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
In our childhood, we all have played many android games like Moto Racing and
Temple run in which by tilting the phone the position of the character changes. So, all
these happen because of the sensors present in your Android device. Most
Android-powered devices have built-in sensors that measure motion, orientation, and
various environmental conditions. Android Sensors can be used to monitor the
three-dimensional device movement or change in the environment of the device such as
light, proximity, rotation, movements, magnetic fields, and much more.
Sensors can be used to monitor the three-dimensional device movement or change in
the environment of the device.
Android provides sensor api to work with different types of sensors.
Types of Sensors
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 is used to get information about the sensor such
as sensor name, sensor type, sensor resolution, sensor type, etc.
3. SensorEvent class: This class is used to find information about the sensor.
Its instance is created by the system. It provides information about the sensor.
Its instance is created by the system. It provides information about the sensor.
It provides two call back methods to get information when sensor values (x,y and z)
change or sensor accuracy changes.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:id="@+id/sensorslist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:text="Sensors"
android:textSize="20dp"
android:textStyle="bold"
android:layout_gravity="center"
android:visibility="gone"/>
</LinearLayout>
Now open your main activity file MainActivity.java from \java\com.tutlane.sensorsexample path and write
the code like as shown below
MainActivity.java
package com.tutlane.sensorsexample;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.List;
File: activity_main.xml
1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <TextView
8. android:id="@+id/textView"
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. android:text="Shake to switch color" />
12.
13. </RelativeLayout>
File: MainActivity.java
1. package com.example.sensor;
2.
3. import android.app.Activity;
4. import android.graphics.Color;
5. import android.hardware.Sensor;
6. import android.hardware.SensorEvent;
7. import android.hardware.SensorEventListener;
8. import android.hardware.SensorManager;
9. import android.os.Bundle;
10. import android.view.View;
11. import android.widget.Toast;
12.
13. public class MainActivity extends Activity implements SensorEventListener{
14. private SensorManager sensorManager;
15. private boolean isColor = false;
16. private View view;
17. private long lastUpdate;
18.
19. @Override
20. public void onCreate(Bundle savedInstanceState) {
21. super.onCreate(savedInstanceState);
22. setContentView(R.layout.activity_main);
23. view = findViewById(R.id.textView);
24. view.setBackgroundColor(Color.GREEN);
25.
26. sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
27. lastUpdate = System.currentTimeMillis();
28. }
29. //overriding two methods of SensorEventListener
30. @Override
31. public void onAccuracyChanged(Sensor sensor, int accuracy) {}
32. @Override
33. public void onSensorChanged(SensorEvent event) {
34. if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
35. getAccelerometer(event);
36. }
37.
38. }
39.
40. private void getAccelerometer(SensorEvent event) {
41. float[] values = event.values;
42. // Movement
43. float x = values[0];
44. float y = values[1];
45. float z = values[2];
46.
47. float accelationSquareRoot = (x * x + y * y + z * z)
48. / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
49.
50. long actualTime = System.currentTimeMillis();
51. Toast.makeText(getApplicationContext(),String.valueOf(accelationSquareRoot)+" "+
52. SensorManager.GRAVITY_EARTH,Toast.LENGTH_SHORT).show();
53.
54. if (accelationSquareRoot >= 2) //it will be executed if you shuffle
55. {
56.
57. if (actualTime - lastUpdate < 200) {
58. return;
59. }
60. lastUpdate = actualTime;//updating lastUpdate for next shuffle
61. if (isColor) {
62. view.setBackgroundColor(Color.GREEN);
63.
64. } else {
65. view.setBackgroundColor(Color.RED);
66. }
67. isColor = !isColor;
68. }
69. }
70.
71. @Override
72. protected void onResume() {
73. super.onResume();
74. // register this class as a listener for the orientation and
75. // accelerometer sensors
76. sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELE
ROMETER),
77. SensorManager.SENSOR_DELAY_NORMAL);
78. }
79.
80. @Override
81. protected void onPause() {
82. // unregister listener
83. super.onPause();
84. sensorManager.unregisterListener(this);
85. }
86. }
Android – Animations
Animation is the process of adding a motion effect to any view, image, or text. With the
help of an animation, you can add motion or can change the shape of a specific view.
Animation in Android is generally used to give your UI a rich look and feel.
Generally, the animations are useful when we want to notify users about the changes
happening in our app, such as new content loaded or new actions available, etc.
1. Fade In Animation
2. Fade Out Animation
3. Cross Fading Animation
4. Blink Animation
5. Zoom In Animation
6. Zoom Out Animation
7. Rotate Animation
8. Move Animation
9. Slide Up Animation
10.Slide Down Animation
11.Bounce Animation
12.Sequential Animation
13.Together Animation
Following is the example of creating XML files under anim folder to define slide up /
down animation properties.
The XML files will contain the code like as shown below based on the type of
animation.
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()
1
This method starts the animation.
setDuration(long duration)
2
This method sets the duration of an animation.
getDuration()
3
This method gets the duration which is set by above method
end()
4
This method ends the animation.
cancel()
5
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 image1 = (ImageView)findViewById(R.id.imageView1);
image.startAnimation(animation);
The following are some of the important animation attributes that will help us to change
the behavior of animation in our application.
Attributes Description
This is only needed if we wish to listen to events like start, end or repeat. For this the
activity must implement AnimationListener and the following methods need to
overridden.
Example-
MainActivity.java.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;
<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="zoom"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="40dp"
android:onClick="zoom "/>
<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 "/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fade"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="fade"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="blink"
android:onClick="blink"
android:id="@+id/button4"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="move"
android:onClick="move"
android:id="@+id/button5"
android:layout_below="@+id/button2"
android:layout_alignRight="@+id/button2"
android:layout_alignEnd="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="slide"
android:onClick="slide"
android:id="@+id/button6"
android:layout_below="@+id/button3"
android:layout_toRightOf="@+id/textView"
android:layout_toEndOf="@+id/textView" />
</RelativeLayout>
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="5000"
android:fromXScale="3.0"
android:toXScale="0.5"
android:fromYScale="3.0"
android:toYScale="0.5"
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%" >
</scale>
</set>
Here is the code of res/anim/clockwise.xml.
To Rotate animation in Anti Clockwise, we need to
set android:fromDegrees and android:toDegrees property values and these will defines a
rotation angles like as shown below.
<!—clockwise-->
<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>
<!—anticlockwise-->
<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>
Here is the code of res/anim/fade.xml.
To use Fade In or Fade Out animations in our android applications, we need to define
a new XML file with <alpha> tag . Here alpha references the opacity of an object. An
object with lower alpha values is more transparent, while an object with higher alpha
values is less transparent, more opaque. Fade in animation is nothing but increasing
alpha value from 0 to 1. Fade out android animation is exactly opposite to fade in,
where we need to decrease the alpha value from 1 to 0.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator" >
<!—fadein-->
<alpha
android:fromAlpha="0"
android:toAlpha="1"
android:duration="2000" >
</alpha>
<!—fadeout-->
<alpha
android:startOffset="2000"
android:fromAlpha="1"
android:toAlpha="0"
android:duration="2000" >
</alpha>
</set>
Here is the code of res/anim/blink.xml.
Here fade in and fade out are performed infinitely in reverse mode each time.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="600"
android:repeatMode="reverse"
android:repeatCount="infinite"/>
</set>
Here is the code of res/anim/move.xml.
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:fillAfter="true">
<translate
android:fromXDelta="0%p"
android:toXDelta="75%p"
android:duration="800" />
</set>
Note- Thw optional %p suffix provides a size relative to some parent container.
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:interpolator="@android:anim/linear_interpolator"
android:toXScale="1.0"
android:toYScale="0.0" />
</set>
WHAT IS SQLITE?
Constructor Description
Method Description
Method Description
getColumnCount()
1 This method return the total number of columns of the
table.
getColumnIndex(String columnName)
2 This method returns the index number of a column by
specifying the name of the column
getColumnName(int columnIndex)
3 This method returns the name of the column by
specifying the index of the column
4 getColumnNames()
This method returns the array of all the column names of
the table.
getCount()
5 This method returns the total number of rows in the
cursor
getPosition()
6 This method returns the current position of the cursor in
the table
isClosed()
7 This method returns true if the cursor is closed and
return false otherwise
2. Reading Data:
To read data from the SQLite Database, create a method in the
DatabaseHelper class. Add the following method:
public List<String> getAllData() {
List<String> data = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM mytable", null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
data.add(name);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return data;
}
Call this method to retrieve all the data stored in the mytable table.
3. Updating Data:
To update data in the SQLite Database, create a method in the
DatabaseHelper class. Add the following method:
public int updateData(long id, String newName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", newName);
int rowsAffected = db.update("mytable", values, "id=?", new
String[]{String.valueOf(id)});
db.close();
return rowsAffected;
}
Pass the ID of the row to be updated along with the new name as
parameters to this method. It will return the number of rows
affected.
4. Deleting Data:
To delete data from the SQLite Database, create a method in the
DatabaseHelper class. Add the following method:
public int deleteData(long id) {
SQLiteDatabase db = this.getWritableDatabase();
int rowsDeleted = db.delete("mytable", "id=?", new
String[]{String.valueOf(id)});
db.close();
return rowsDeleted;
}
Pass the ID of the row to be deleted as a parameter to this method. It
will return the number of rows deleted.
Example of android SQLite database
acivity_main.xml
android:background="@android:color/holo_blue_dark">
<TextView
android:text="Username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="12dp"
android:id="@+id/textView"
android:textSize="18sp"
android:textStyle="bold|italic"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:gravity="center" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editName"
android:textStyle="bold|italic"
android:layout_below="@+id/textView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Enter Name"
android:gravity="center_vertical|center" />
<TextView
android:text="Password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="13dp"
android:id="@+id/textView2"
android:textStyle="bold|italic"
android:textSize="18sp"
android:layout_below="@+id/editName"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:gravity="center"
android:hint="Enter Password" />
<Button
android:text="View_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:textSize="18sp"
android:onClick="viewdata"
android:textStyle="bold|italic"
android:layout_alignBaseline="@+id/button"
android:layout_alignBottom="@+id/button"
android:layout_alignRight="@+id/button4"
android:layout_alignEnd="@+id/button4" />
<Button
android:text="add_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:textStyle="bold|italic"
android:textSize="18sp"
android:onClick="addUser"
android:layout_marginLeft="28dp"
android:layout_marginStart="28dp"
android:layout_below="@+id/editPass"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="23dp" />
<Button
android:text="Update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button3"
android:onClick="update"
android:textStyle="normal|bold"
android:layout_below="@+id/editText3"
android:layout_alignLeft="@+id/button4"
android:layout_alignStart="@+id/button4"
android:layout_marginTop="13dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editText6"
android:layout_alignTop="@+id/button4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:freezesText="false"
android:hint="Enter Name to Delete Data"
android:layout_toLeftOf="@+id/button2"
android:layout_toStartOf="@+id/button2" />
<Button
android:text="delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="21dp"
android:layout_marginEnd="21dp"
android:id="@+id/button4"
android:onClick="delete"
android:textStyle="normal|bold"
tools:ignore="RelativeOverlap"
android:layout_marginBottom="41dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_marginTop="47dp"
android:id="@+id/editText3"
android:textStyle="bold|italic"
android:textSize="14sp"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="7dp"
android:layout_marginStart="7dp"
android:hint="Current Name" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:layout_marginTop="11dp"
android:id="@+id/editPass"
android:hint="Enter Password"
android:gravity="center_vertical|center"
android:textSize="18sp"
android:layout_below="@+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textAllCaps="false"
android:textStyle="normal|bold" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editText5"
android:textStyle="bold|italic"
android:textSize="14sp"
android:hint="New Name"
android:layout_alignTop="@+id/button3"
android:layout_alignLeft="@+id/editText3"
android:layout_alignStart="@+id/editText3"
android:layout_marginTop="32dp" />
</RelativeLayout>
Mainactivity.java
package com.example.mydb;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
}
public void addUser(View view)
{
String t1 = Name.getText().toString();
String t2 = Pass.getText().toString();
if(t1.isEmpty() || t2.isEmpty())
{
Toast.makeText(getApplicationContext(), "Enter Both
Name and Password", Toast.LENGTH_LONG).show();
}
else
{
long id = db.insertData(t1,t2);
if(id<=0)
{
Toast.makeText(getApplicationContext(), "Insertion
UnSuccessful", Toast.LENGTH_LONG).show();
Name.setText("");
Pass.setText("");
} else
{
Toast.makeText(getApplicationContext(), "Insertion
Successful", Toast.LENGTH_LONG).show();
Name.setText("");
Pass.setText("");
}
}
}
}
else
{
int a= db.updateName( u1, u2);
if(a<=0)
{
Toast.makeText(getApplicationContext(),
"Unsuccessful", Toast.LENGTH_LONG).show();
updateold.setText("");
updatenew.setText("");
} else {
Toast.makeText(getApplicationContext(), "Updated",
Toast.LENGTH_LONG).show();
updateold.setText("");
updatenew.setText("");
}
}
}
public void delete( View view)
{
String uname = delete.getText().toString();
if(uname.isEmpty())
{
Toast.makeText(getApplicationContext(), "Enter Data",
Toast.LENGTH_LONG).show();
}
else{
int a= db.delete(uname);
if(a<=0)
{
Toast.makeText(getApplicationContext(),
"Unsuccessful", Toast.LENGTH_LONG).show();
delete.setText("");
}
else
{
Toast.makeText(getApplicationContext(), "DELETED",
Toast.LENGTH_LONG).show();
delete.setText("");
}
}
}
}
myDbHelper.java
package com.example.abhidb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
public class myDbHelper extends SQLiteOpenHelper
{
private static final String DATABASE_NAME =
"myDatabase"; // Database Name
private static final String TABLE_NAME = "myTable"; //
Table Name
private static final int DATABASE_Version = 1; // Database
Version
private static final String UID="_id"; // Column I (Primary
Key)
private static final String NAME = "Name"; //Column II
private static final String MyPASSWORD= "Password"; //
Column III
private static final String CREATE_TABLE = "CREATE
TABLE "+TABLE_NAME+
" ("+UID+" INTEGER PRIMARY KEY
AUTOINCREMENT, "+NAME+" VARCHAR(255) ,"+
MyPASSWORD+" VARCHAR(225));";
private static final String DROP_TABLE ="DROP TABLE IF
EXISTS "+TABLE_NAME;
private Context context;