Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Android Emulator

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 32

Dalvik Virtual Machine | DVM

As we know the modern JVM is high performance and provides excellent memory
management. But it needs to be optimized for low-powered handheld devices as well.

The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile
devices. It optimizes the virtual machine for memory, battery life and performance.

Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.

The Dex compiler converts the class files into the .dex file that run on the Dalvik VM.
Multiple class files are converted into one dex file.
Let's see the compiling and packaging process from the source file:

The javac tool compiles the java source file into the class file.
The dx tool takes all the class files of your application and generates a single .dex file. It
is a platform-specific tool.
The Android Assets Packaging Tool (aapt) handles the packaging process.

AndroidManifest.xml file in android

The AndroidManifest.xml file contains information of your package, including


components of the application such as activities, services, broadcast receivers, content
providers etc.
It performs some other tasks also:
o It is responsible to protect the application to access any protected parts by
providing the permissions.
o It also declares the android api that the application is going to use.
o It lists the instrumentation classes. The instrumentation classes provides
profiling and other informations. These informations are removed just before the
application is published etc.
This is the required xml file for all the android application and located inside the root
directory.
A simple AndroidManifest.xml file looks like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.javatpoint.hello"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

1. </manifest>
Elements of the AndroidManifest.xml file
The elements used in the above xml file are described below.
<manifest>

manifest is the root element of the AndroidManifest.xml file. It has package attribute
that describes the package name of the activity class.

<application>
application is the subelement of the manifest. It includes the namespace declaration.
This element contains several subelements that declares the application component
such as activity etc.
The commonly used attributes are of this element are icon, label, theme etc.
android:icon represents the icon for all the android application components.
android:label works as the default label for all the application components.
android:theme represents a common theme for all the android activities.
<activity>
activity is the subelement of application and represents an activity that must be
defined in the AndroidManifest.xml file. It has many attributes such as label, name,
theme, launchMode etc.
android:label represents a label i.e. displayed on the screen.
android:name represents a name for the activity class. It is required attribute.
<intent-filter>
intent-filter is the sub-element of activity that describes the type of intent to which
activity, service or broadcast receiver can respond to.
<action>
It adds an action for the intent-filter. The intent-filter must have at least one action
element.
<category>
It adds a category name to an intent-filter.

1. Android Emulator
The Android emulator is an Android Virtual Device (AVD), which represents a
specific Android device. We can use the Android emulator as a target device to execute
and test our Android application on our PC. The Android emulator provides almost all the
functionality of a real device. We can get the incoming phone calls and text messages. It
also gives the location of the device and simulates different network speeds. Android
emulator simulates rotation and other hardware sensors. It accesses the Google Play
store, and much more
Testing Android applications on emulator are sometimes faster and easier than doing on
a real device. For example, we can transfer data faster to the emulator than to a real
device connected through USB.
The Android emulator comes with predefined configurations for several Android phones,
Wear OS, tablet, Android TV devices.

Requirement and recommendations

The Android emulator takes additional requirements beyond the basic system
requirement for Android Studio. These requirements are given below:
o SDK Tools 26.1.1 or higher
o 64-bit processor
o Windows: CPU with UG (unrestricted guest) support
o HAXM 6.2.1 or later (recommended HAXM 7.2.0 or later)
o
Install the emulator
The Android emulator is installed while installing the Android Studio. However some
components of emulator may or may not be installed while installing Android Studio. To
install the emulator component, select the Android Emulator component in the SDK
Tools tab of the SDK Manager.

Run an Android app on the Emulator


We can run an Android app form the Android Studio project, or we can run an app which
is installed on the Android Emulator as we run any app on a device.
To start the Android Emulator and run an application in our project:
1. In Android Studio, we need to create an Android Virtual Device (AVD) that the
emulator can use to install and run your app. To create a new AVD:-
1.1 Open the AVD Manager by clicking Tools > AVD Manager.
1.2 Click on Create Virtual Device, at the bottom of the AVD Manager dialog.
Then Select Hardware page appears.

1.3 Select a hardware profile and then click Next. If we don?t see the hardware profile
we want, then we can create or import a hardware profile. The System Image page
appears.

1.4 Select the system image for the particular API level and click Next. This leads to
open a Verify Configuration page.
1.5 Change AVD properties if needed, and then click Finish.
2. In the toolbar, choose the AVD, which we want to run our app from the target device
from the drop-down menu.

3. Click Run.
Launch the Emulator without first running an app
To start the emulator:
1. Open the AVD Manager.
2. Double-click an AVD, or click Run
While the emulator is running, we can run the Android Studio project and select the
emulator as the target device. We can also drag an APKs file to install on an emulator,
and then run them.
3. Android Activity Lifecycle
In android, Activity represents a single screen with a user interface (UI) of an
application and it will acts an entry point for users to interact with an app.

Generally, the android apps will contain multiple screens and each screen of our
application will be an extension of Activity class. By using activities, we can place all our
android application UI components in a single screen.
From the multiple activities in android app, one activity can be marked as a main
activity and that is the first screen to appear when we launch the application. In android
app each activity can start another activity to perform different actions based on our
requirements.

For example, a contacts app which is having multiple activities, in that the main activity
screen will show a list of contacts and from the main activity screen we can launch other
activities that provide screens to perform tasks like add a new contact and search for
the contacts. All these activities in the contact app are loosely bound to other activities
but will work together to provide a better user experience.

Generally, in android there is a minimal dependency between the activities in an app. To


use activities in application we need to register those activities information in our app’s
manifest file (AndroidMainfest.xml) and need to manage activity life cycle properly.
To use activities in our application we need to define an activities with required
attributes in manifest file (AndroidMainfest.xml) like as shown below
<?xml version="1.0" encoding="utf-8"?>
<manifest …..>
<application …..>
<activity android:name=".MainActivity" >
…….
…….
</activity>
…….
</application>
</manifest>
The activity attribute android:name will represent the name of class and we can also
add multiple attributes like icon, label, theme, permissions, etc. to an activity element
based on our requirements.

In android application, activities can be implemented as a subclass of Activity class like


as shown below.

public class MainActivity extends Activity {

}
This is how we can activities in android application based on our requirements.

Android Activity Lifecycle


Generally, the activities in our android application will go through a different stages in
their life cycle. In android, Activity class have 7 callback methods
like onCreate(), onStart(), onPause(), onRestart(), onResume(), onStop() and onDestroy()
to describe how the activity will behave at different stages.

By using activity cal-back methods we can define how our activity can behave when the
user enter or leaves our application.

Android Activity Lifecycle Callback Methods


In android, an activity goes through a series of states during its lifetime. By using
callback methods we can get the activity transitions between the states.
Android system initiates its program within an Activity starting with a call
on onCreate() callback method. There is a sequence of callback methods that start up an
activity and a sequence of callback methods that tear down an activity.

This section will give you detailed information about callback methods to handle activity
transitions between states during the lifecycle.

onCreate()
This is the first callback method and it fires when the system creates an activity for the
first time. During the activity creation, activity entered into a Created state.

If we have an application start-up logic that needs to perform only once during the life
cycle of an activity, then we can write that logic in onCreate() method.

Following is the example of defining a onCreate() method in android activity.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Once onCreate() method execution is finished, the activity will enter into Started state
and the system calls the onStart() method.

onStart()
The onStart() callback method will invoke when an activity entered into Started State
by completing onCreate() method. The onStart() method will make an activity visible to
the user and this method execution will finish very quickly.

Following is the example of defining a onStart() method in android activity.

@Override
protected void onStart()
{
super.onStart()
}
After completion of onStart() method execution, the activity enters into Resumed state
and system invoke the onResume() method.

onResume()
When an activity entered into Resumed state, the system invokes onResume() call back
method. In this state activity start interacting with the user that means user can see the
functionality and designing part of an application on the single screen.

Mostly the core functionality of an app is implemented in onResume() method.

The app will stay in this Resumed state until an another activity happens to take focus
away from the app like getting a phone call or screen turned off, etc.

In case if any interruption events happen in Resumed state, the activity will enter
into Paused state and the system will invoke onPause() method.
After an activity returned from Paused state to Resumed state, the system again will
call onResume() method due to this we need to implement onResume() method to
initialize the components that we release during onPause() method

Following is the example of defining a onResume() method in android activity.

@Override
public void onResume() {
super.onResume();
if (mCamera == null) {
initializeCamera();
}
}
If any interruption happens in Resumed state, the activity will enter into Paused state
and the system will invoke onPause() method.

onPause()
Whenever the user leaves an activity or the current activity is being Paused then the
system invokes onPause() method. The onPause() method is used to pause operations
like stop playing the music when the activity is in a paused state or pass an activity
while switching from one app to another app because every time only one app can be
focused.

Following is the example of defining a onPause() method in android activity.

@Override
public void onPause() {
super.onPause();
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
After completion of onPause() method execution, the next method is
either onStop() or onResume() depending on what happens after an activity entered into
a Paused state.

onStop()
The system will invoke onStop() callback method when an activity no longer visible to
the user, the activity will enter into Stopped state. This happens due to current activity
entered into Resumed state or newly launched activity covers complete screen or it’s
been destroyed.

The onStop() method is useful to release all the app resources which are no longer
needed to the user.

Following is the example of defining a onStop() method in android activity.

@Override
protected void onStop()
{
super.onStop();
}
The next callback method which raised by the system is either onRestart(), in case if the
activity coming back to interact with the user or onDestroy(), in case if the activity
finished running.

onRestart()
The system will invoke onRestart() method when an activity restarting itself after
stopping it. The onRestart() method will restore the state of activity from the time that is
being stopped.

The onRestart() callback method in android activity will always be followed


by onStart() method.

onDestroy()
The system will invoke onDestroy() method before an activity is destroyed and this is the
final callback method received by the android activity.

The system will invoke this onDestory() callback method either the activity is finishing or
system destroying the activity to save space.

Following is the example of defining a onDestroy() method in android activity.

@Override
public void onDestroy()
{
super.onDestroy();
}
The onDestroy() method will release all the resources which are not released by previous
callback onStop() method.

Android Activity Lifecycle Diagram


Generally, in android activity class uses different callback methods
like onCreate(), onStart(), onPause(), onRestart(), onResume(), onStop() and onDestroy()
to go through a different stages of activity life cycle.

Following is the pictorial representation of the Android Activity Life cycle which shows
how Activity will behave in different stages using callback methods.
Whenever the user trying to leave an activity like switching from one app to another
app, the system will use callback methods to dismantle the activity completely or
partially to resume the activity from where the user left off.

Based on our requirements we can implement the activity in the android app using the
callback method and it’s not necessary to use all callback methods in each android
application.

package com.tutlane.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Activity Lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("Activity Lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("Activity Lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("Activity Lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("Activity Lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("Activity Lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("Activity Lifecycle","onDestroy invoked");
}
}

3.Different Types of Activities in Android Studio


Android Studio is the official IDE (Integrated Development Environment) for
Android application development and it is based on JetBrains’ IntelliJ IDEA software.
Android Studio provides many excellent features that enhance productivity when
building Android apps, such as:
 A flexible Gradle-based build system
 A fast and feature-rich emulator
 A blended environment where one can develop for all Android devices
 Apply Changes to push code and resource changes to the running app without
restarting the app
 GitHub and Code template integration to assist you to develop common app features
and import sample code
 Extensive testing tools and frameworks
 C++ and NDK support
 Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud
Messaging and App Engine and many more.
Generally, when a developer wants to create a new project in the android studio he/she
needs to select a project template which is consisting of many activities as shown in
the below image. (Considering that the developer developing the android app for
phone and tablet). So in this article, we are going to discuss what do these activities
mean in brief. Here is the list of activities:
1. No Activity
2. Basic Activity
3. Bottom Navigation Activity
4. Empty Activity
5. Fullscreen Activity
6. Google Admob Ads Activity
7. Google Maps Activity
8. Login Activity
9. Master/Detail Flow
10. Navigation Drawer Activity
11. Settings Activity
12. Scrolling Activity
13. Tabbed Activity
14. Fragment + ViewModel
15. Native C++

(1) No Activity
As the name suggests No Activity means creating a new empty project. When the
developer selects this activity there will be neither an XML file nor a Java/Kotlin file. No
files are automatically generated when you select No Activity. The project structure will
look like the following:

(2) Basic Activity


Basic Activity creates a new basic activity with the navigation component. When the
developer selects the basic activity, then you will be getting a menu button, and you
will also get a floating action button. These files are automatically created when you
select Basic Activity:

(3) Bottom Navigation Activity


Bottom Navigation Activity creates a new activity with bottom navigations. We all have
come across apps that contain a Bottom Navigation Bar . Some popular examples
include Instagram, WhatsApp, etc. These files are automatically created when you
select Bottom Navigation Activity and the following is the welcome page:

(4) Empty Activity


This is a popular activity and we frequently select this activity when we start
developing an android project. It simply creates a new empty activity.
Note: Please mark the phase in No activity and Empty Activity. In No Activity, it
creates a new empty project and in Empty Activity, it creates new empty activity.
Please refer to Introduction to Activities in Android to get more information about the
activities in android.
These files are automatically created when you select Empty Activity and the following
is the welcome page:
(5) Fullscreen Activity
Fullscreen activity creates a new activity that toggles the visibility of the system UI
(status and navigation bars) and action bar upon user interaction. Many apps are using
Full-Screen Activity to have an attractive screen to show slides etc. These files are
automatically created when you select Fullscreen Activity and the following is the
welcome page:

(6) Google Admob Ads Activity


To earn money from the Android app or game, there are many ways such as in-App
Purchases, Sponsorship, Advertisements, and many more. But there is another popular
method to earn money from the Android app is by integrating an advertisement e.g
known as Google AdMob. Google AdMob is designed with developers in mind, AdMob
helps to earn more app revenue, deliver better user experience, and surface actionable
insights all with automated tools that do the hard work for you. There are mainly four
types of flexible, high-performing format available in Google AdMob
 Native: Ads that you design to fit the app, seamlessly
 Interstitial: Full-screen ads that capture attention and become part of the
experience.
 Banner: Traditional formats in a variety of placements.
 Rewarded Video: An immersive, user-initiated video ad that rewards users for
watching.
In Android Studio Google Admob Ads Activity creates an activity with AdMob Ad
fragment. These files are automatically created when you select Google Admob Ads
Activity and the following is the welcome page:
(7) Google Maps Activity
Android permits to integrate google maps in our application. One can show any
location on the map or can show various routes on the map etc. One can also
customize the map according to the choices. So Google Maps Activity creates a new
activity with a Google Map. These files are automatically created when you select
Google Maps Activity and the following is the welcome page:

(8) Login Activity


As the name suggests Login Activity creates a new login activity, allowing users to
enter an email address and password to log in or to register with the application. Login
Activity is one of the most common activities that almost every application contains
this activity. These files are automatically created when you select Login Activity and
the following is the welcome page:
(9) Master/Detail Flow
Master/Detail Flow creates a new master/detail flow, enabling users to view a collection
of objects as well as details for each object. This flow is presented using two columns
on tablet-sized screens and one column on handsets and smaller screens. This
template creates two activities, a master fragment, and a detailed fragment. These
files are automatically created when you select Master/Detail Flow and the following is
the welcome page:

(10) Navigation Drawer Activity


Android Navigation Drawer is a sliding left menu that is used to display the important
links in the application. The Navigation drawer makes it easy to navigate to and from
between those links. It’s not visible by default and it needs to open either by sliding
from left or clicking its icon in the ActionBar. In broader terms, Navigation Drawer is an
overlay panel, which is a replacement of an activity screen that was especially
dedicated to showing all the options and links in the application. These files are
automatically created when you select Navigation Drawer and the following is the
welcome page:
(11) Settings Activity
Setting Activity creates a new activity that allows a user to configure application
settings. These files are automatically created when you select Settings Activity and
the following is the welcome page:

(12) Scrolling Activity


Scrolling activity is an essential activity to have in the app as it provides the users with
a perfect view when the layout is long. It creates a new vertical scrolling activity. These
files are automatically created when you select Scrolling activity and the following is
the welcome page:
(13) Tabbed Activity
In Android, TabLayout gives a horizontal layout to display tabs. If TabLayout is used
then along with it, Fragment is also used, because fragments are lightweight and the
app can have more functionality on a single screen if more fragments are added.
Whenever the user clicks on the tab it will lead to the transaction of one Fragment to
another. ViewPager is used to swipe between the tabs. WhatsApp, Facebook, etc. are
a perfect example of TabLayout with ViewPager. This is how a TabLayout looks like.

Tabbed Activity creates a new blank activity with tabs. These files are automatically
created when you select Tabbed Activity and the following is the welcome page:

(14) Fragment + ViewModel


As the name suggests Fragment + ViewModel creates a new activity and a fragment
with the view model.
 Fragment: A Fragment is a piece of an activity which enable more modular activity
design. A fragment encapsulates functionality so that it is easier to reuse within
activities and layouts.
 ViewModel: It exposes those data streams which are relevant to the View.
Moreover, it servers as a link between the Model and the View. Model: This layer is
responsible for the abstraction of the data sources. Model and ViewModel work
together to get and save the data. View: The purpose of this layer is to inform the
ViewModel about the user’s action. This layer observes the ViewModel and does not
contain any kind of application logic.
These files are automatically created when you select Fragment + ViewModel and the
following is the welcome page:

(15) Native C++


Native C++ creates a new project with an empty activity configured to use JNI. JNI is
the Java Native Interface. JNI describes a way for the bytecode that Android compiles
from executed code that is written in the Java or Kotlin programming languages to
interact with native code that is written in C/C++. JNI is vendor-neutral, has support for
loading code from dynamic shared libraries, and while cumbersome at times is
efficient.

5.Android Application Components (Activities, Intents, Views, Layouts,


Services)

The following are the basic core application components that can be used in Android
application.

 Activities
 Intents
 Content Providers
 Broadcast Receivers
 Services
All these application components are defined in the android app description file
(AndroidMainfest.xml) like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<manifest …..>
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" ……>
<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>
This is how we can define an android application components
in AndroidManiFest.xml file.

Android Activities
In android, Activity represents a single screen with a user interface (UI) and it will acts
an entry point for the user’s to interact with app.

For example, a contacts app that is having multiple activities like showing a list of
contacts, add a new contact, and another activity to search for the contacts. All these
activities in the contact app are independent of each other but will work together to
provide a better user experience.

To know more about Activities in android check Android Activities.

Android Intents
In android, Intent is a messaging object which is used to request an action from another
component.

In android, intents are mainly used to perform the following things.

 Starting an Activity
 Starting a Service
 Delivering a Broadcast
There are two types of intents available in android, those are

1. Implicit Intents
2. Explicit Intents
To know more about Intents in android check this Android Intents.

Android Services
In android, Service is a component that keeps an app running in the background to
perform long-running operations based on our requirements. For Service, we don’t have
any user interface and it will run the apps in background like play music in background
when the user in different app.

We have two types of services available in android, those are

 Local Services
 Remote Services
To know more about Services in android check this Android Services.
Android Broadcast Receivers
In android, Broadcast Receiver is a component that will allow a system to deliver events
to the app like sending a low battery message to the app. The apps can also initiate
broadcasts to let other apps know that required data available in a device to use it.

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.

To know more about Broadcast Receivers in android check this Android Broadcast
Receivers.

Android Content Providers


In android, Content Providers are useful to exchange the data between the apps based
on the requests. The Content Providers can share the app data that stores in the file
system, SQLite database, on the web or any other storage location that our app can
access.

By using Content Providers, other apps can query or modify the data of our app based
on the permissions provided by content provider. For example, android provides a
Content Provider (ContactsContract.Data) to manage contacts information, by using
proper permissions any app can query the content provider to perform read and write
operations on contacts information.

To know more about Content Providers in android check this Android Content Provider.

Additional Components
In android, we have additional components which are used to build the relationship
between the above components (Activities, Intents, Content
Providers, Services and Broadcast Receivers) to implement our application logic, those
are

Compon
ent Description

Fragment These are used to represent the portion of user interface in an


s activity

Layouts These are used to define the user interface (UI) for an activity or
app

Views These are used to build a user interface for an app using UI
elements like buttons, lists, etc.

Resources To build an android app we required external elements like


images, audio files, etc. other than coding

Manifest It’s a configuration file (AndroidManifest.xml) for the application


File and it will contain the information about Activities, Intents, Content
Providers, Services, Broadcast Receivers, permissions, etc.
These are the main application components which are required to build an android
application based on our requirements.
How to make android apps
In this page, you will know how to create the simple hello android application. We are
creating the simple example of android using the Eclipse IDE. For creating the simple
example:
1. Create the new android project
2. Write the message (optional)
3. Run the android application

Hello Android Example


You need to follow the 3 steps mentioned above for creating the Hello android
application.
1) Create the New Android project
For creating the new android studio project:
1) Select Start a new Android Studio project
ADVERTISEMENT

2) Provide the following information: Application name, Company domain, Project


location and Package name of application and click next.

3) Select the API level of application and click next.


4) Select the Activity type (Empty Activity).

5) Provide the Activity Name and click finish.

After finishing the Activity configuration, Android Studio auto generates the activity class
and other required configuration files.
Now an android project has been created. You can explore the android project and see
the simple program, it looks like this:
2) Write the message
File: activity_main.xml
Android studio auto generates code for activity_main.xml file. You may edit this file
according to your requirement.
1. <?xml version="1.0" encoding="utf-8"?>
2. <android.support.constraint.ConstraintLayout xmlns:android="http://
schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context="first.javatpoint.com.welcome.MainActivity">
8.
9. <TextView
10. android:layout_width="wrap_content"
11. android:layout_height="wrap_content"
12. android:text="Hello Android!"
13. app:layout_constraintBottom_toBottomOf="parent"
14. app:layout_constraintLeft_toLeftOf="parent"
15. app:layout_constraintRight_toRightOf="parent"
16. app:layout_constraintTop_toTopOf="parent" />
17.
18. </android.support.constraint.ConstraintLayout>
19. }
File: MainActivity.java
1. package first.javatpoint.com.welcome;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {
9. super.onCreate(savedInstanceState);
10. setContentView(R.layout.activity_main);
11. }
12. }
To understand the first android application, visit the next page (internal details of hello
android example).

3) Run the android application


To run the android application, click the run icon on the toolbar or simply press Shift +
F10.
Android Toast Example

Andorid Toast can be used to display information for the short period of time. A toast
contains message to be displayed quickly and disappears after sometime.
The android.widget.Toast class is the subclass of java.lang.Object class.
You can also create custom toast as well for example toast displaying image. You can
visit next page to see the code for custom toast.

Toast class
Toast class is used to show notification for a particular interval of time. After sometime it
disappears. It doesn't block the user interaction.
Constants of Toast class
There are only 2 constants of Toast class which are given below.
Constant Description

public static final int displays view for the long duration
LENGTH_LONG of time.

public static final int displays view for the short duration
LENGTH_SHORT of time.
Methods of Toast class
The widely used methods of Toast class are given below.
Method Description

public static Toast makeText(Context context, makes the toast containing text
CharSequence text, int duration) and duration.

public void show() displays toast.

public void setMargin (float horizontalMargin, float changes the horizontal and vertical
verticalMargin) margin difference.

Android Toast Example


1. Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show(
);
Another code:
1. Toast toast=Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_S
HORT);
2. toast.setMargin(50,50);
3. toast.show();
Here, getApplicationContext() method returns the instance of Context.

Full code of activity class displaying Toast


Let's see the code to display the toast.
File: MainActivity.java
1. package example.javatpoint.com.toast;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.widget.Toast;
6.
7. public class MainActivity extends AppCompatActivity {
8.
9. @Override
10. protected void onCreate(Bundle savedInstanceState) {
11. super.onCreate(savedInstanceState);
12. setContentView(R.layout.activity_main);
13.
14. //Displaying Toast with Hello Javatpoint message
15. Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).
show();
16. }
17. }

Output:

How to Send Data From One Activity to Second Activity in Android?


Last Updated : 08 Feb, 2023



This article aims to tell and show how to “Send the data from one activity to
second activity using Intent”. In this example, we have two
activities, activity_first which are the source activity, and activity_second which is the
destination activity. We can send the data using the putExtra() method from one activity
and get the data from the second activity using the getStringExtra() method.
In this example, one EditText is used to input the text. This text is sent to the second
activity when the “Send” button is clicked. For this, Intent will start and the following
methods will run:
 putExtra() method is used for sending the data, data in key-value pair key is
variable name and value can be Int, String, Float, etc.
 getStringExtra() method is for getting the data(key) that is sent by the above
method. According to the data type of value, there are other methods
like getIntExtra(), getFloatExtra()
How to Create an Android App to Send and Receive the Data between Two
Activity
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New
Project in Android Studio. The code for that has been given in both Java and Kotlin
Programming Language for Android. This will create an XML file and a Java File.
Please refer to the prerequisites to learn more about this step.

Step 2: Working with the XML Files


Next, go to the activity_main.xml file, which represents the UI of the project. Below
is the code for the activity_main.xml file. Comments are added inside the code to
understand the code in more detail. Open the “activity_first_activity.xml” file and add
the following widgets in a Relative Layout.
 An EditText to Input the message
 A Button to send the data
Also, Assign the ID to each component along with other attributes as shown in the
image and the code below. The assigned ID on a component helps that component to
be easily found and used in the Java/Kotlin files.
Syntax:
android:id="@+id/id_name"
Here the given IDs are as follows:
 Send Button: send_button_id
 input EditText: send_text_id
 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"
android:layout_height="match_parent"
tools:context=".first_activity">

<EditText
android:id="@+id/send_text_id"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="20dp"
android:hint="Input"
android:textSize="25dp"
android:textStyle="bold" />

<Button
android:id="@+id/send_button_id"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginLeft="150dp"
android:layout_marginTop="150dp"
android:text="send"
android:textStyle="bold" />
</RelativeLayout>
This will make the UI of the Application

Step 3: Working with the MainActivity File


Go to the MainActivity File and refer to the following code. Below is the code for the
MainActivity File. Comments are added inside the code to understand the code in more
detail. Now, after the UI, this step will create the Backend of the App. For this, open the
“first_activity” file and instantiate the components made in the XML file (EditText, send
Button) using findViewById() method. This method binds the created object to the UI
Components with the help of the assigned ID.
Syntax: General
ComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);
Syntax: for components used is as follows:
Button send_button= findViewById(R.id.send_button_id);
send_text = findViewById(R.id.send_text_id);
Setting up the Operations for the Sending and Receiving of Data.
These Operations are as follows:
Add the listener to the send button and this button will send the data.
This is done as follows:
send_button.setOnClickListener(v -> {}
after clicking this button following operation will be performed. Now create the String
type variable to store the value of EditText which is input by the user. Get the value
and convert it to a string.
This is done as follows:
String str = send_text.getText().toString();
Now create the Intent object First_activity.java class to Second_activity class.
This is done as follows:
Intent intent = new Intent(getApplicationContext(), Second_activity.class);
where getApplicationContext() will fetch the current activity. Put the value in the
putExtra method in the key-value pair then start the activity.
This is done as follows:
intent.putExtra("message_key", str);
startActivity(intent);
where “str” is the string value and the key is “message_key” this key will use to get the
str value
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class first_activity extends AppCompatActivity {
// define the variable
Button send_button;
EditText send_text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_activity);

send_button = findViewById(R.id.send_button_id);
send_text = findViewById(R.id.send_text_id);
// add the OnClickListener in sender button after clicked this button following
Instruction will run
send_button.setOnClickListener(v -> {
// get the value which input by user in EditText and convert it to string
String str = send_text.getText().toString();
// Create the Intent object of this class Context() to Second_activity class
Intent intent = new Intent(getApplicationContext(), Second_activity.class);
// now by putExtra method put the value in key, value pair key is
// message_key by this key we will receive the value, and put the string
intent.putExtra("message_key", str);
// start the Intent
startActivity(intent);
});
}
}
Step 4: Creating Second_Activity to Receive the Data.
The steps to create the second activity are as follows:
android project > File > new > Activity > Empty Activity

Step 5: Working with the Second XML File


Add TextView to display the received messages. assign an ID to Textview.
 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"
android:layout_height="match_parent"
tools:context="org.geeksforgeeks.navedmalik.sendthedata.Second_activity">
<TextView
android:id="@+id/received_value_id"
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_marginLeft="40dp"
android:layout_marginTop="20dp"
android:textSize="40sp"
android:textStyle="bold"
android:layout_marginStart="40dp" />
</RelativeLayout>
The Second Activity is shown below:
Step 6: Working with the SecondActivity File
Define the TextView variable, use findViewById() to get the TextView as shown above.
receiver_msg = (TextView) findViewById(R.id.received_value_id);
Now In the second_activity.java file create the object of getIntent to receive the value
in String type variable by the getStringExtra method using message_key.
Intent intent = getIntent();
String str = intent.getStringExtra("message_key");
The received value set in the TextView object of the second activity XML file
receiver_msg.setText(str);
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import
androidx.appcompat.app.AppCompatActivity;
public class Second_activity extends
AppCompatActivity {
TextView receiver_msg;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_acti
vity);
receiver_msg =
findViewById(R.id.received_value_id);
// create the get Intent object
Intent intent = getIntent();
// receive the value by getStringExtra()
method and
// key must be same which is send by first
activity
String str =
intent.getStringExtra("message_key");
// display the string into textView
receiver_msg.setText(str);
}
}

You might also like