Android
Android
It is developed by Google and later the OHA (Open Handset Alliance). Java language
is mainly used to write the android code even though other languages can be used.
The goal of android project is to create a successful real-world product that improves
the mobile experience for end users.
There are many code names of android such as Lollipop, Kitkat, Jelly Bean, Ice cream
Sandwich, Froyo, Ecliar, Donut etc which is covered in next page.
Features of Android
After learning what is android, let's see the features of android. The important
features of android are given below:
1) It is open-source.
3) There are a lot of mobile applications that can be chosen by the consumer.
4) It provides many interesting features like weather details, opening screen, live RSS
(Really Simple Syndication) feeds etc.
It provides support for messaging services(SMS and MMS), web browser, storage
(SQLite), connectivity (GSM, CDMA, Blue Tooth, Wi-Fi etc.), media, handset layout etc.
o Entertainment
o Tools
o Communication
o Productivity
o Personalization
o Music and Audio
o Social
o Media and Video
o Travel and Local etc.
History of Android
The history and versions of android are interesting to know. The code names of
android ranges from A to J currently, such
as Aestro, Blender, Cupcake, Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice
Cream Sandwitch, Jelly Bean, KitKat and Lollipop. Let's understand the android
history in a sequence.
3) The key employees of Android Incorporation are Andy Rubin, Rich Miner, Chris
White and Nick Sears.
4) Originally intended for camera but shifted to smart phones later because of low
market for camera only.
5) Android is the nick name of Andy Rubin given by coworkers because of his love to
robots.
1.5 Cupcake 3
1.6 Donut 4
2.1 Eclair 7
2.2 Froyo 8
4.4 KitKat 19
5.0 Lollipop 21
6.0 Marshmallow 23
Here, we are going to tell you, the required softwares to develop android
applications using Eclipse IDE.
1. By ADT Bundle
2. By Setup Eclipse Manually
1) By Android Studio
It is the simplest technique to install required software for android application. It
includes:
o Eclipse IDE
o Android SDK
o Eclipse Plugin
If you download the Android Studio from android site, you don't need to have
eclipse IDE, android SDK and eclipse Plugin because it is already included in Android
Studio.
If you have downloaded the Android Studio, unjar it, go to eclipse IDE and start the
eclipse by clicking on the eclipse icon. You don't need to do any extra steps here.
Android Architecture
android architecture or Android software stack is categorized into five parts:
1. linux kernel
2. native libraries (middleware),
3. Android Runtime
4. Application Framework
5. Applications
1) Linux kernel
It is the heart of android architecture that exists at the root of android
architecture. Linux kernel is responsible for device drivers, power management,
memory management, device management and resource access.
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.
The WebKit library is responsible for browser support, SQLite is for database,
FreeType for font support, Media for playing and recording audio and video formats.
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.
Android Core Building Blocks
An android component is simply a piece of code that has a well defined life cycle
e.g. Activity, Receiver, Service etc.
Activity
View
A view is the UI element such as button, label, text field etc. Anything that you see is
a view.
Intent
For example, you may write the following code to view the webpage.
1. Intent intent=new Intent(Intent.ACTION_VIEW);
2. intent.setData(Uri.parse("http://www.javatpoint.com"));
3. startActivity(intent);
Service
There are two types of services local and remote. Local service is accessed from
within the application whereas remote service is accessed remotely from other
applications running on the same device.
Content Provider
Fragment
Fragments are like parts of activity. An activity can display one or more fragments on
the screen at the same time.
AndroidManifest.xml
It is used to test the android application without the need for mobile or tablet etc. It
can be created in different configurations to emulate different types of real devices.
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.
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.
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:
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.
or
For example, if we execute the emulator from Android Studio on a Mac, the default
command line will be similar as follows:
1. $ emulator -list-avds
o To run an Android emulator that uses an AVD, double-click the AVD, or click Launch
o To stop the running emulator, right-click and select Stop, or click Menu ▼ and select
Stop.
o If we want to clear the data from an emulator and return it to the initial state when it
was first defined, then right-click an AVD and select Wipe Data. Or click menu ▼ and
select Wipe Data.
Now an android project has been created. You can explore the android project and
see the simple program, it looks like this:
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).
The android emulator might take 2 or 3 minutes to boot. So please have patience.
After booting the emulator, the android studio installs the application and launches
the activity. You will see something like this:
Internal Details of Hello Android
Example
Here, we are going to learn the internal details or working of hello android example.
Android application contains different components such as java source code, string
resources, images, manifest file, apk file etc. Let's understand the project structure of
android application.
Let's see the java source file created by the Eclipse IDE:
File: MainActivity.java
1. package com.example.helloandroid;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.view.Menu;
5. import android.widget.TextView;
6. public class MainActivity extends Activity {//(1)
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {//(2)
9. super.onCreate(savedInstanceState);
10.
11. setContentView(R.layout.activity_main);//(3)
12. }
13. @Override
14. public boolean onCreateOptionsMenu(Menu menu) {//(4)
15. // Inflate the menu; this adds items to the action bar if it is present.
16. getMenuInflater().inflate(R.menu.activity_main, menu);
17. return true;
18. }
19. }
(1) Activity is a java class that creates and default window on the screen where we
can place different components such as Button, EditText, TextView, Spinner etc. It is
like the Frame of Java AWT.
It provides life cycle methods for activity such as onCreate, onStop, OnResume etc.
(2) The onCreate method is called when Activity class is first created.
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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. <TextView
7. android:layout_width="wrap_content"
8. android:layout_height="wrap_content"
9. android:layout_centerHorizontal="true"
10. android:layout_centerVertical="true"
11. android:text="@string/hello_world" />
12. </RelativeLayout>
As you can see, a textview is created by the framework automatically. But the
message for this string is defined in the strings.xml file.
The @string/hello_world provides information about the textview message. The
value of the attribute hello_world is defined in the strings.xml file.
File: strings.xml
You can change the value of the hello_world attribute from this file.
It is the auto-generated file that contains IDs for all the resources of res directory. It
is generated by aapt(Android Asset Packaging Tool). Whenever you create any
component on activity_main, a corresponding ID is created in the R.java file which
can be used in the Java Source file later.
File: R.java
APK File
An apk file is created by the framework automatically. If you want to run the android
application on the mobile, transfer and install it.
Resources
Manifest file
For more information about manifest file visit here: AndroidManifest.xml file.
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.
This is the required xml file for all the android application and located inside the root
directory.
<manifest>
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.
<activity>
<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>
Let's see the android R.java file. It includes a lot of static nested classes such as menu,
id, layout, attr, drawable, string etc.
1. this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
activity_main.xml
File: activity_main.xml
Activity class
File: MainActivity.java
1. package first.javatpoint.com.hidetitlebar;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.Window;
6. import android.view.WindowManager;
7.
8. public class MainActivity extends AppCompatActivity {
9.
10. @Override
11. protected void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
Syntax:
1. <activity android:name="package_name.Your_ActivityName"
2. android:screenOrientation="orirntation_type">
3. </activity>
Example:
Value Description
unspecified It is the default value. In such case, system chooses the orientation.
activity_main.xml
File: activity_main.xml
Activity class
File: MainActivity.java
1. package example.javatpoint.com.screenorientation;
2.
3. import android.content.Intent;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.widget.Button;
8.
9. public class MainActivity extends AppCompatActivity {
10.
11. Button button1;
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16.
17. button1=(Button)findViewById(R.id.button1);
18. }
19. public void onClick(View v) {
20. Intent intent = new Intent(MainActivity.this,SecondActivity.class);
21. startActivity(intent);
22. }
23. }
activity_second.xml
File: activity_second.xml
1. package example.javatpoint.com.screenorientation;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class SecondActivity extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_second);
12.
13. }
14. }
AndroidManifest.xml
File: AndroidManifest.xml
Android widgets are easy to learn. The widely used android widgets with examples
are given below:
Android Button
Android Toast
Custom Toast
We are able to customize the toast, such as we can display image on the toast
ToggleButton
CheckBox
AlertDialog
AlertDialog displays a alert dialog containing the message with OK and Cancel
buttons.
Spinner
Spinner displays the multiple options, but only one can be selected at a time.
AutoCompleteTextView
RatingBar
Datepicker displays the datepicker dialog that can be used to pick the date.
TimePicker
TimePicker displays the timepicker dialog that can be used to pick the time.
ProgressBar
1. button.setOnClickListener(new View.OnClickListener() {
2. @Override
3. public void onClick(View view) {
4. //code
5. }
6. });
1. <Button
2. android:onClick="methodName"
3. />
Drag the component or write the code for UI in
activity_main.xml
First of all, drag 2 textfields from the Text Fields palette and one button from the
Form Widgets palette as shown in the following figure.
The generated code for the ui components will be like this:
File: activity_main.xml
Activity class
Now write the code to display the sum of two numbers.
File: MainActivity.java
1. package example.javatpoint.com.sumoftwonumber;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.EditText;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
11. private EditText edittext1, edittext2;
12. private Button buttonSum;
13.
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. addListenerOnButton();
20. }
21.
22. public void addListenerOnButton() {
23. edittext1 = (EditText) findViewById(R.id.editText1);
24. edittext2 = (EditText) findViewById(R.id.editText2);
25. buttonSum = (Button) findViewById(R.id.button);
26.
27. buttonSum.setOnClickListener(new View.OnClickListener() {
28. @Override
29. public void onClick(View view) {
30. String value1=edittext1.getText().toString();
31. String value2=edittext2.getText().toString();
32. int a=Integer.parseInt(value1);
33. int b=Integer.parseInt(value2);
34. int sum=a+b;
35. Toast.makeText(getApplicationContext(),String.valueOf(sum), Toast.L
ENGTH_LONG).show();
36. }
37. });
38. }
39. }
Output:
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.
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.
There are only 2 constants of Toast class which are given below.
Constant Description
public static final int LENGTH_LONG displays view for the long duration of time.
public static final int LENGTH_SHORT displays view for the short duration of time.
Method Description
public static Toast makeText(Context context, makes the toast containing text and
CharSequence text, int duration) duration.
public void setMargin (float horizontalMargin, float changes the horizontal and vertical
verticalMargin) margin difference.
Another code:
1. Toast toast=Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.L
ENGTH_SHORT);
2. toast.setMargin(50,50);
3. toast.show();
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:
activity_main.xml
Drag the component that you want to display on the main activity.
File: activity_main.xml
customtoast.xml
Create another xml file inside the layout directory. Here we are having ImageView
and TextView in this xml file.
File: customtoast.xml
Activity class
File: MainActivity.java
1. package example.javatpoint.com.customtoast;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.Gravity;
6. import android.view.LayoutInflater;
7. import android.view.View;
8. import android.view.ViewGroup;
9. import android.widget.Toast;
10.
11. public class MainActivity extends AppCompatActivity {
12.
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17.
18. //Creating the LayoutInflater instance
19. LayoutInflater li = getLayoutInflater();
20. //Getting the View object as defined in the customtoast.xml file
21. View layout = li.inflate(R.layout.customtoast,(ViewGroup) findViewById(R.i
d.custom_toast_layout));
22.
23. //Creating the Toast object
24. Toast toast = new Toast(getApplicationContext());
25. toast.setDuration(Toast.LENGTH_SHORT);
26. toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
27. toast.setView(layout);//setting the view of custom toast layout
28. toast.show();
29. }
30. }
Output:
Android ToggleButton Example
It is beneficial if user have to change the setting between two states. It can be used
to On/Off Sound, Wifi, Bluetooth etc.
Since Android 4.0, there is another type of toggle button called switch that provides
slider control.
Android ToggleButton and Switch both are the subclasses of CompoundButton class.
Method Description
CharSequence getTextOff() Returns the text when button is not in the checked
state.
CharSequence getTextOn() Returns the text for when button is in the checked
state.
Drag two toggle button and one button for the layout. Now the activity_main.xml file
will look like this:
File: activity_main.xml
File: MainActivity.java
1. package example.javatpoint.com.togglebutton;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.Toast;
8. import android.widget.ToggleButton;
9.
10. public class MainActivity extends AppCompatActivity {
11. private ToggleButton toggleButton1, toggleButton2;
12. private Button buttonSubmit;
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17.
18. addListenerOnButtonClick();
19. }
20.
21. public void addListenerOnButtonClick(){
22. //Getting the ToggleButton and Button instance from the layout xml file
23. toggleButton1=(ToggleButton)findViewById(R.id.toggleButton);
24. toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);
25. buttonSubmit=(Button)findViewById(R.id.button);
26.
27. //Performing action on button click
28. buttonSubmit.setOnClickListener(new View.OnClickListener(){
29.
30. @Override
31. public void onClick(View view) {
32. StringBuilder result = new StringBuilder();
33. result.append("ToggleButton1 : ").append(toggleButton1.getText());
34. result.append("\nToggleButton2 : ").append(toggleButton2.getText());
35. //Displaying the message in toast
36. Toast.makeText(getApplicationContext(), result.toString(),Toast.LENGTH_LON
G).show();
37. }
38.
39. });
40.
41. }
42. }
Output:
Android CheckBox Example
There can be a lot of usage of checkboxes. For example, it can be used to know the
hobby of the user, activate/deactivate the specific action etc.
There are many inherited methods of View, TextView, and Button classes in the
CheckBox class. Some of them are as follows:
Method Description
Drag the three checkboxes and one button for the layout. Now the activity_main.xml
file will look like this:
File: activity_main.xml
Activity class
File: MainActivity.java
1. package example.javatpoint.com.checkbox;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.CheckBox;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
11. CheckBox pizza,coffe,burger;
12. Button buttonOrder;
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17. addListenerOnButtonClick();
18. }
19. public void addListenerOnButtonClick(){
20. //Getting instance of CheckBoxes and Button from the activty_main.xml file
21. pizza=(CheckBox)findViewById(R.id.checkBox);
22. coffe=(CheckBox)findViewById(R.id.checkBox2);
23. burger=(CheckBox)findViewById(R.id.checkBox3);
24. buttonOrder=(Button)findViewById(R.id.button);
25.
26. //Applying the Listener on the Button click
27. buttonOrder.setOnClickListener(new View.OnClickListener(){
28.
29. @Override
30. public void onClick(View view) {
31. int totalamount=0;
32. StringBuilder result=new StringBuilder();
33. result.append("Selected Items:");
34. if(pizza.isChecked()){
35. result.append("\nPizza 100Rs");
36. totalamount+=100;
37. }
38. if(coffe.isChecked()){
39. result.append("\nCoffe 50Rs");
40. totalamount+=50;
41. }
42. if(burger.isChecked()){
43. result.append("\nBurger 120Rs");
44. totalamount+=120;
45. }
46. result.append("\nTotal: "+totalamount+"Rs");
47. //Displaying the message on the toast
48. Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LO
NG).show();
49. }
50.
51. });
52. }
53. }
Output:
Android Custom CheckBox
Android provides facility to customize the UI of view elements rather than default.
You are able to create custom CheckBox in android. So, you can add some different
images of checkbox on the layout.
activity_main.xml
File: activity_main.xml
checkbox.xml
File: checkbox.xml
1. package example.javatpoint.com.customcheckbox;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.CheckBox;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
11. CheckBox cb1,cb2;
12. Button button;
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17. cb1=(CheckBox)findViewById(R.id.checkBox3);
18. cb2=(CheckBox)findViewById(R.id.checkBox4);
19. button=(Button)findViewById(R.id.button);
20.
21. button.setOnClickListener(new View.OnClickListener() {
22. @Override
23. public void onClick(View v) {
24. StringBuilder sb=new StringBuilder("");
25.
26. if(cb1.isChecked()){
27. String s1=cb1.getText().toString();
28. sb.append(s1);
29. }
30.
31. if(cb2.isChecked()){
32. String s2=cb2.getText().toString();
33. sb.append("\n"+s2);
34.
35. }
36. if(sb!=null && !sb.toString().equals("")){
37. Toast.makeText(getApplicationContext(), sb, Toast.LENGTH_LONG
).show();
38.
39. }
40. else{
41. Toast.makeText(getApplicationContext(),"Nothing Selected", Toas
t.LENGTH_LONG).show();
42. }
43.
44. }
45.
46. });
47. }
48. }
Output
Android RadioButton
RadioButton is a two states button which is either checked or unchecked. If a single
radio button is unchecked, we can click it to make checked radio button. Once a
radio button is checked, it cannot be marked as unchecked by user.
1. package example.javatpoint.com.radiobutton;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.RadioButton;
8. import android.widget.RadioGroup;
9. import android.widget.Toast;
10.
11. public class MainActivity extends AppCompatActivity {
12. Button button;
13. RadioButton genderradioButton;
14. RadioGroup radioGroup;
15. @Override
16. protected void onCreate(Bundle savedInstanceState) {
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19. radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
20. }
21. public void onclickbuttonMethod(View v){
22. int selectedId = radioGroup.getCheckedRadioButtonId();
23. genderradioButton = (RadioButton) findViewById(selectedId);
24. if(selectedId==-1){
25. Toast.makeText(MainActivity.this,"Nothing selected", Toast.LENGTH_S
HORT).show();
26. }
27. else{
28. Toast.makeText(MainActivity.this,genderradioButton.getText(), Toast.LENGTH_S
HORT).show();
29. }
30.
31. }
32. }
Output
Android Dynamic RadioButton
Instead of creating RadioButton through drag and drop from palette, android also
facilitates you to create it programmatically (dynamically). For creating dynamic
RadioButton, we need to use android.view.ViewGroup.LayoutParams which
configures the width and height of views and
implements setOnCheckedChangeListener() method of RadioGroup class.
activity_main.xml
File: activity_main.xml
1. package com.example.test.dynamicradiobutton;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.widget.RadioButton;
6. import android.widget.RadioGroup;
7. import android.widget.RelativeLayout;
8.
9. import android.widget.RelativeLayout.LayoutParams;
10. import android.widget.Toast;
11.
12. public class MainActivity extends AppCompatActivity {
13. RadioGroup rg;
14. RelativeLayout rl;
15. RadioButton rb1,rb2;
16.
17. @Override
18. protected void onCreate(Bundle savedInstanceState) {
19. super.onCreate(savedInstanceState);
20. setContentView(R.layout.activity_main);
21.
22. rg = new RadioGroup(this);
23. rl = (RelativeLayout) findViewById(R.id.relativeLayout);
24. rb1 = new RadioButton(this);
25. rb2 = new RadioButton(this);
26.
27. rb1.setText("Male");
28. rb2.setText("Female");
29. rg.addView(rb1);
30. rg.addView(rb2);
31. rg.setOrientation(RadioGroup.HORIZONTAL);
32.
33. RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParam
s((int) LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);
34. params.leftMargin =150;
35. params.topMargin = 100;
36.
37. rg.setLayoutParams(params);
38. rl.addView(rg);
39.
40. rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
41. @Override
42. public void onCheckedChanged(RadioGroup group, int checkedId) {
43. RadioButton radioButton = (RadioButton) findViewById(checkedId);
44. Toast.makeText(getApplicationContext(),radioButton.getText(),Toast.LENGTH
_LONG).show();
45. }
46. });
47. }
48. }
Android Custom RadioButton
Rather than default user interface of android RadioButton, we can also implement a
custom radio button. Custom RadioButton makes user interface more attractive.
activity_main.xml
File: activity_main.xml
File: checkbox.xml
1. package com.example.test.customradiobutton;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.RadioButton;
8. import android.widget.RadioGroup;
9. import android.widget.Toast;
10.
11. public class MainActivity extends AppCompatActivity {
12. Button button;
13. RadioButton genderradioButton;
14. RadioGroup radioGroup;
15. @Override
16. protected void onCreate(Bundle savedInstanceState) {
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19.
20. radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
21. }
22.
23.
24. public void onclickbuttonMethod(View v){
25. int selectedId = radioGroup.getCheckedRadioButtonId();
26. genderradioButton = (RadioButton) findViewById(selectedId);
27. if(selectedId==-1){
28. Toast.makeText(MainActivity.this,"Nothing selected", Toast.LENGTH_SHORT).sh
ow();
29. }
30. else{
31. Toast.makeText(MainActivity.this,genderradioButton.getText(), Toast.LE
NGTH_SHORT).show();
32. }
33.
34. }
35. }
Output
Android AlertDialog Example
Android AlertDialog can be used to display the dialog message with OK and Cancel
buttons. It can be used to interrupt and ask the user about his/her choice to continue
or discontinue.
Android AlertDialog is composed of three regions: title, content area and action
buttons.
public AlertDialog.Builder setIcon(int) This method is used to set the icon over
AlertDialog.
activity_main.xml
You can have multiple components, here we are having only a textview.
File: activity_main.xml
strings.xml
Optionally, you can store the dialog message and title in the strings.xml file.
File: strings.xml
1. <resources>
2. <string name="app_name">AlertDialog</string>
3. <string name="dialog_message">Welcome to Alert Dialog</string>
4. <string name="dialog_title">Javatpoint Alert Dialog</string>
5. </resources>
Activity class
1. package example.javatpoint.com.alertdialog;
2.
3. import android.content.DialogInterface;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.widget.Button;
8. import android.app.AlertDialog;
9. import android.widget.Toast;
10.
11. public class MainActivity extends AppCompatActivity {
12. Button closeButton;
13. AlertDialog.Builder builder;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. closeButton = (Button) findViewById(R.id.button);
20. builder = new AlertDialog.Builder(this);
21. closeButton.setOnClickListener(new View.OnClickListener() {
22. @Override
23. public void onClick(View v) {
24.
25. //Uncomment the below code to Set the message and title from the
strings.xml file
26. builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
27.
28. //Setting message manually and performing action on button click
29. builder.setMessage("Do you want to close this application ?")
30. .setCancelable(false)
31. .setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
32. public void onClick(DialogInterface dialog, int id) {
33. finish();
34. Toast.makeText(getApplicationContext(),"you choose yes action fo
r alertbox",
35. Toast.LENGTH_SHORT).show();
36. }
37. })
38. .setNegativeButton("No", new DialogInterface.OnClickListener() {
39. public void onClick(DialogInterface dialog, int id) {
40. // Action for 'NO' Button
41. dialog.cancel();
42. Toast.makeText(getApplicationContext(),"you choose no action for
alertbox",
43. Toast.LENGTH_SHORT).show();
44. }
45. });
46. //Creating dialog box
47. AlertDialog alert = builder.create();
48. //Setting the title manually
49. alert.setTitle("AlertDialogExample");
50. alert.show();
51. }
52. });
53. }
54. }
Output:
Android Spinner Example
Android Spinner is like the combox box of AWT or Swing. It can be used to display
the multiple options to the user in which only one item can be selected by the user.
Android spinner is like the drop down menu with multiple values from which the end
user can select only one value.
Android spinner is associated with AdapterView. So you need to use one of the
adapter classes with spinner.
activity_main.xml
Drag the Spinner from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
Activity class
Let's write the code to display item on the spinner and perform event handling.
File: MainActivity.java
1. package example.javatpoint.com.spinner;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.AdapterView;
7. import android.widget.ArrayAdapter;
8. import android.widget.Spinner;
9. import android.widget.Toast;
10.
11. public class MainActivity extends AppCompatActivity implements
12. AdapterView.OnItemSelectedListener {
13. String[] country = { "India", "USA", "China", "Japan", "Other"};
14.
15. @Override
16. protected void onCreate(Bundle savedInstanceState) {
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19. //Getting the instance of Spinner and applying OnItemSelectedListener o
n it
20. Spinner spin = (Spinner) findViewById(R.id.spinner);
21. spin.setOnItemSelectedListener(this);
22.
23. //Creating the ArrayAdapter instance having the country list
24. ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,
country);
25. aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdow
n_item);
26. //Setting the ArrayAdapter data on the Spinner
27. spin.setAdapter(aa);
28.
29. }
30.
31. //Performing action onItemSelected and onNothing selected
32. @Override
33. public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
long id) {
34. Toast.makeText(getApplicationContext(),country[position] , Toast.LENGTH_LONG)
.show();
35. }
36. @Override
37. public void onNothingSelected(AdapterView<?> arg0) {
38. // TODO Auto-generated method stub
39. }
40. }
Output:
Android AutoCompleteTextView
Example
Drag the AutoCompleteTextView and TextView from the pallete, now the
activity_main.xml file will like this:
File: activity_main.xml
File: MainActivity.java
1. package example.javatpoint.com.autocompletetextview;
2.
3. import android.graphics.Color;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.widget.ArrayAdapter;
7. import android.widget.AutoCompleteTextView;
8.
9. public class MainActivity extends AppCompatActivity {
10. String[] language ={"C","C++","Java",".NET","iPhone","Android","ASP.NET","PHP"};
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_main);
15. //Creating the instance of ArrayAdapter containing list of language name
s
16. ArrayAdapter<String> adapter = new ArrayAdapter<String>
17. (this,android.R.layout.select_dialog_item,language);
18. //Getting the instance of AutoCompleteTextView
19. AutoCompleteTextView actv = (AutoCompleteTextView)findViewById(R.i
d.autoCompleteTextView);
20. actv.setThreshold(1);//will start working from first character
21. actv.setAdapter(adapter);//setting the adapter data into the AutoComplet
eTextView
22. actv.setTextColor(Color.RED);
23. }
24. }
Output:
Android ListView
Android ListView is a view which contains the group of items and displays in a
scrollable list. ListView is implemented by importing android.widget.ListView class.
ListView is a default scrollable which does not use other scroll view.
ListView uses Adapter classes which add the content from data source (such as string
array, array, database etc) to ListView. Adapter bridges data between
an AdapterViews and other Views (ListView, ScrollView etc).
Example of ListView
Let's implement a simple listview example.
File: activity_main.xml
Create an additional mylist.xml file in layout folder which contains view components
displayed in listview.
mylist.xml
File: mylist.xml
strings.xml
File:strings.xml
1. <resources>
2. <string name="app_name">ListView</string>
3. <string-array name="array_technology">
4. <item>Android</item>
5. <item>Java</item>
6. <item>Php</item>
7. <item>Hadoop</item>
8. <item>Sap</item>
9. <item>Python</item>
10. <item>Ajax</item>
11. <item>C++</item>
12. <item>Ruby</item>
13. <item>Rails</item>
14. <item>.Net</item>
15. <item>Perl</item>
16. </string-array>
17. </resources>
Activity class
In java class we need to add adapter to listview using setAdapter() method of
listview.
File: MainActivity.java
1. package listview.example.com.listview;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.AdapterView;
7. import android.widget.ArrayAdapter;
8. import android.widget.ListView;
9. import android.widget.TextView;
10. import android.widget.Toast;
11.
12. public class MainActivity extends AppCompatActivity {
13. ListView listView;
14. TextView textView;
15. String[] listItem;
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_main);
20.
21. listView=(ListView)findViewById(R.id.listView);
22. textView=(TextView)findViewById(R.id.textView);
23. listItem = getResources().getStringArray(R.array.array_technology);
24. final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
25. android.R.layout.simple_list_item_1, android.R.id.text1, listItem);
26. listView.setAdapter(adapter);
27.
28. listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
29. @Override
30. public void onItemClick(AdapterView<?> adapterView, View view, int positio
n, long l) {
31. // TODO Auto-generated method stub
32. String value=adapter.getItem(position);
33. Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT
).show();
34.
35. }
36. });
37. }
38. }
Output
Android Custom ListView (Adding
Images, sub-title)
After creating simple ListView, android also provides facilities to customize our
ListView.
As the simple ListView, custom ListView also uses Adapter classes which added the
content from data source (such as string array, array, database etc). Adapter bridges
data between an AdapterViews and other Views
activity_main.xml
Create an activity_main.xml file in layout folder.
File: activity_main.xml
Create an additional mylist.xml file in layout folder which contains view components
displayed in listview.
mylist.xml
File: mylist.xml
Activity class
File: MainActivity.java
1. package com.example.test.listviewwithimage;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.AdapterView;
7. import android.widget.ListView;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
11. ListView list;
12.
13. String[] maintitle ={
14. "Title 1","Title 2",
15. "Title 3","Title 4",
16. "Title 5",
17. };
18.
19. String[] subtitle ={
20. "Sub Title 1","Sub Title 2",
21. "Sub Title 3","Sub Title 4",
22. "Sub Title 5",
23. };
24.
25. Integer[] imgid={
26. R.drawable.download_1,R.drawable.download_2,
27. R.drawable.download_3,R.drawable.download_4,
28. R.drawable.download_5,
29. };
30. @Override
31. protected void onCreate(Bundle savedInstanceState) {
32. super.onCreate(savedInstanceState);
33. setContentView(R.layout.activity_main);
34.
35. MyListAdapter adapter=new MyListAdapter(this, maintitle, subtitle,imgid
);
36. list=(ListView)findViewById(R.id.list);
37. list.setAdapter(adapter);
38.
39.
40. list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
41.
42. @Override
43. public void onItemClick(AdapterView<?> parent, View view,int positio
n, long id) {
44. // TODO Auto-generated method stub
45. if(position == 0) {
46. //code specific to first list item
47. Toast.makeText(getApplicationContext(),"Place Your First Option
Code",Toast.LENGTH_SHORT).show();
48. }
49.
50. else if(position == 1) {
51. //code specific to 2nd list item
52. Toast.makeText(getApplicationContext(),"Place Your Second Option Code
",Toast.LENGTH_SHORT).show();
53. }
54.
55. else if(position == 2) {
56.
57. Toast.makeText(getApplicationContext(),"Place Your Third Option
Code",Toast.LENGTH_SHORT).show();
58. }
59. else if(position == 3) {
60.
61. Toast.makeText(getApplicationContext(),"Place Your Forth Option
Code",Toast.LENGTH_SHORT).show();
62. }
63. else if(position == 4) {
64.
65. Toast.makeText(getApplicationContext(),"Place Your Fifth Option
Code",Toast.LENGTH_SHORT).show();
66. }
67.
68. }
69. });
70. }
71. }
MyListView.java
1. package com.example.test.listviewwithimage;
2.
3. import android.app.Activity;
4.
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8. import android.widget.ArrayAdapter;
9. import android.widget.ImageView;
10. import android.widget.TextView;
11.
12. public class MyListAdapter extends ArrayAdapter<String> {
13.
14. private final Activity context;
15. private final String[] maintitle;
16. private final String[] subtitle;
17. private final Integer[] imgid;
18.
19. public MyListAdapter(Activity context, String[] maintitle,String[] subtitle, Int
eger[] imgid) {
20. super(context, R.layout.mylist, maintitle);
21. // TODO Auto-generated constructor stub
22.
23. this.context=context;
24. this.maintitle=maintitle;
25. this.subtitle=subtitle;
26. this.imgid=imgid;
27.
28. }
29.
30. public View getView(int position,View view,ViewGroup parent) {
31. LayoutInflater inflater=context.getLayoutInflater();
32. View rowView=inflater.inflate(R.layout.mylist, null,true);
33.
34. TextView titleText = (TextView) rowView.findViewById(R.id.title);
35. ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
36. TextView subtitleText = (TextView) rowView.findViewById(R.id.subtitle);
37.
38. titleText.setText(maintitle[position]);
39. imageView.setImageResource(imgid[position]);
40. subtitleText.setText(subtitle[position]);
41.
42. return rowView;
43.
44. };
45. }
Output
Android RatingBar Example
Android RatingBar can be used to get the rating from the user. The Rating returns a
floating-point number. It may be 2.0, 3.5, 4.0 etc.
Android RatingBar displays the rating in stars. Android RatingBar is the subclass of
AbsSeekBar class.
The getRating() method of android RatingBar class returns the rating number.
activity_main.xml
Drag the RatingBar and Button from the pallete, now the activity_main.xml file will
like this:
File: activity_main.xml
Activity class
File: MainActivity.java
1. package example.javatpoint.com.ratingbar;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.RatingBar;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
11. RatingBar ratingbar;
12. Button button;
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17. addListenerOnButtonClick();
18. }
19. public void addListenerOnButtonClick(){
20. ratingbar=(RatingBar)findViewById(R.id.ratingBar);
21. button=(Button)findViewById(R.id.button);
22. //Performing action on Button Click
23. button.setOnClickListener(new View.OnClickListener(){
24.
25. @Override
26. public void onClick(View arg0) {
27. //Getting the rating and displaying it on the toast
28. String rating=String.valueOf(ratingbar.getRating());
29. Toast.makeText(getApplicationContext(), rating, Toast.LENGTH_LON
G).show();
30. }
31.
32. });
33. }
34. }
Output:
Android WebView Example
Android WebView is used to display web page in android. The web page can be
loaded from same application or URL. It is used to display online content in android
activity.
The loadUrl() and loadData() methods of Android WebView class are used to load
and display web page.
Let's see the simple code to display HTML web page using web view. In this case,
html file must be located inside the asset directory.
1. WebView mywebview = (WebView) findViewById(R.id.webView1);
2. mywebview.loadUrl("file:///android_asset/myresource.html");
activity_main.xml
File: activity_main.xml
To add the web page (.html, .jsp) locally in application, they are required to place in
the assets folder. An assets folder is created as: right click on app -> New -> Folder -
> Assets Folder ->main or simply create an assets directory inside main directory.
Activity class
File: MainActivity.java
1. package example.javatpoint.com.webview;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.webkit.WebView;
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. WebView mywebview = (WebView) findViewById(R.id.webView);
14. // mywebview.loadUrl("https://www.javatpoint.com/");
15.
16. /*String data = "<html><body><h1>Hello, Javatpoint!</h1></body></html>";
17. mywebview.loadData(data, "text/html", "UTF-8"); */
18.
19. mywebview.loadUrl("file:///android_asset/myresource.html");
20. }
21. }
Output:
Android SeekBar and RatingBar classes are the sub classes of AbsSeekBar.
Drag the seek bar from the pallete, now activity_main.xml will look like this:
File: activity_main.xml
Let's see the Activity class displaying seek bar and performing event handling.
File: MainActivity.java
1. package example.javatpoint.com.seekbar;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.widget.SeekBar;
6. import android.widget.Toast;
7.
8. public class MainActivity extends AppCompatActivity {
9. SeekBar seekBar;
10. @Override
11. protected void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. setContentView(R.layout.activity_main);
14.
15. seekBar=(SeekBar)findViewById(R.id.seekBar);
16. seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
17. @Override
18. public void onProgressChanged(SeekBar seekBar, int progress,
19. boolean fromUser) {
20. Toast.makeText(getApplicationContext(),"seekbar progress: "+progress, Toas
t.LENGTH_SHORT).show();
21. }
22.
23. @Override
24. public void onStartTrackingTouch(SeekBar seekBar) {
25. Toast.makeText(getApplicationContext(),"seekbar touch started!", To
ast.LENGTH_SHORT).show();
26. }
27.
28. @Override
29. public void onStopTrackingTouch(SeekBar seekBar) {
30. Toast.makeText(getApplicationContext(),"seekbar touch stopped!", Toast.LE
NGTH_SHORT).show();
31. }
32. });
33. }
34. }
Output:
Android DatePicker Example
Android DatePicker is a widget to select date. It allows you to select date by day,
month and year. Like DatePicker, android also provides TimePicker to select time.
activity_main.xml
File: activity_main.xml
Activity class
File: MainActivity.java
1. package example.javatpoint.com.datepicker;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.DatePicker;
8. import android.widget.TextView;
9.
10. public class MainActivity extends AppCompatActivity {
11. DatePicker picker;
12. Button displayDate;
13. TextView textview1;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. textview1=(TextView)findViewById(R.id.textView1);
20. picker=(DatePicker)findViewById(R.id.datePicker);
21. displayDate=(Button)findViewById(R.id.button1);
22.
23. textview1.setText("Current Date: "+getCurrentDate());
24.
25. displayDate.setOnClickListener(new View.OnClickListener(){
26. @Override
27. public void onClick(View view) {
28.
29. textview1.setText("Change Date: "+getCurrentDate());
30. }
31.
32. });
33.
34. }
35. public String getCurrentDate(){
36. StringBuilder builder=new StringBuilder();;
37. builder.append((picker.getMonth() + 1)+"/");//month is 0 based
38. builder.append(picker.getDayOfMonth()+"/");
39. builder.append(picker.getYear());
40. return builder.toString();
41. }
42. }
Output:
Android TimePicker Example
Android TimePicker widget is used to select date. It allows you to select time by
hour and minute. You cannot select time by seconds.
activity_main.xml
File: activity_main.xml
Activity class
File: MainActivity.java
1. package example.javatpoint.com.timepicker;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.widget.Button;
7. import android.widget.TextView;
8. import android.widget.TimePicker;
9.
10. public class MainActivity extends AppCompatActivity {
11. TextView textview1;
12. TimePicker timepicker;
13. Button changetime;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. textview1=(TextView)findViewById(R.id.textView1);
20. timepicker=(TimePicker)findViewById(R.id.timePicker);
21. //Uncomment the below line of code for 24 hour view
22. timepicker.setIs24HourView(true);
23. changetime=(Button)findViewById(R.id.button1);
24.
25. textview1.setText(getCurrentTime());
26.
27. changetime.setOnClickListener(new View.OnClickListener(){
28. @Override
29. public void onClick(View view) {
30. textview1.setText(getCurrentTime());
31. }
32. });
33.
34. }
35.
36. public String getCurrentTime(){
37. String currentTime="Current Time: "+timepicker.getCurrentHour()
+":"+timepicker.getCurrentMinute();
38. return currentTime;
39. }
40.
41. }
Output:
Android analog and digital clocks are used to show time in android application.
Android DigitalClock is the subclass of TextView class. Since Android API level 17, it
is deprecated. You are recommended to use TextClock Instead.
The AnalogClock was deprecated in API level 23. This widget is no longer supported.
Instead if you want to use AnalogClock in your application you need to hard code. It
does not appear in API level 27 to drag from palette.
Note: Analog and Digital clocks cannot be used to change the time of the device.
To do so, you need to use DatePicker and TimePicker.
In android, you need to drag analog and digital clocks from the pallet to display
analog and digital clocks.
activity_main.xml
Now, drag the analog and digital clocks, now the xml file will look like this.
File: activity_main.xml
Activity class
File: MainActivity.java
1. package example.javatpoint.com.analogdigital;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_main);
12. }
13. }
Output:
We can display the android progress bar dialog box to display the status of work
being done e.g. downloading file, analyzing status of work etc.
In this example, we are displaying the progress dialog for dummy file download
operation.
activity_main.xml
Drag one button from the pallete, now the activity_main.xml file will look like this:
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentTop="true"
12. android:layout_centerHorizontal="true"
13. android:layout_marginTop="116dp"
14. android:text="download file" />
15.
16. </RelativeLayout>
Activity class
Let's write the code to display the progress bar dialog box.
File: MainActivity.java
1. package example.javatpoint.com.progressbar;
2.
3. import android.app.ProgressDialog;
4. import android.os.Handler;
5. import android.support.v7.app.AppCompatActivity;
6. import android.os.Bundle;
7. import android.view.View;
8. import android.widget.Button;
9.
10. public class MainActivity extends AppCompatActivity {
11. Button btnStartProgress;
12. ProgressDialog progressBar;
13. private int progressBarStatus = 0;
14. private Handler progressBarHandler = new Handler();
15. private long fileSize = 0;
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_main);
20. addListenerOnButtonClick();
21. }
22. public void addListenerOnButtonClick() {
23. btnStartProgress = findViewById(R.id.button);
24. btnStartProgress.setOnClickListener(new View.OnClickListener(){
25.
26. @Override
27. public void onClick(View v) {
28. // creating progress bar dialog
29. progressBar = new ProgressDialog(v.getContext());
30. progressBar.setCancelable(true);
31. progressBar.setMessage("File downloading ...");
32. progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
33. progressBar.setProgress(0);
34. progressBar.setMax(100);
35. progressBar.show();
36. //reset progress bar and filesize status
37. progressBarStatus = 0;
38. fileSize = 0;
39.
40. new Thread(new Runnable() {
41. public void run() {
42. while (progressBarStatus < 100) {
43. // performing operation
44. progressBarStatus = doOperation();
45. try {
46. Thread.sleep(1000);
47. } catch (InterruptedException e) {
48. e.printStackTrace();
49. }
50. // Updating the progress bar
51. progressBarHandler.post(new Runnable() {
52. public void run() {
53. progressBar.setProgress(progressBarStatus);
54. }
55. });
56. }
57. // performing operation if file is downloaded,
58. if (progressBarStatus >= 100) {
59. // sleeping for 1 second after operation completed
60. try {
61. Thread.sleep(1000);
62. } catch (InterruptedException e) {
63. e.printStackTrace();
64. }
65. // close the progress bar dialog
66. progressBar.dismiss();
67. }
68. }
69. }).start();
70. }//end of onClick method
71. });
72. }
73. // checking how much file is downloaded and updating the filesize
74. public int doOperation() {
75. //The range of ProgressDialog starts from 0 to 10000
76. while (fileSize <= 10000) {
77. fileSize++;
78. if (fileSize == 1000) {
79. return 10;
80. } else if (fileSize == 2000) {
81. return 20;
82. } else if (fileSize == 3000) {
83. return 30;
84. } else if (fileSize == 4000) {
85. return 40; // you can add more else if
86. }
87. /* else {
88. return 100;
89. }*/
90. }//end of while
91. return 100;
92. }//end of doOperation
93. }
Output:
activity_main.xml
Now, drag ScrollView from palette to activity_main.xml file and place some palette
element inside it.
File: activity_main.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. android:paddingBottom="@dimen/activity_vertical_margin"
7. android:paddingLeft="@dimen/activity_horizontal_margin"
8. android:paddingRight="@dimen/activity_horizontal_margin"
9. android:paddingTop="@dimen/activity_vertical_margin"
10. tools:context="com.example.test.scrollviews.MainActivity">
11.
12.
13. <TextView
14. android:layout_width="wrap_content"
15. android:layout_height="wrap_content"
16. android:textAppearance="?android:attr/textAppearanceMedium"
17. android:text="Vertical ScrollView example"
18. android:id="@+id/textView"
19. android:layout_gravity="center_horizontal"
20. android:layout_centerHorizontal="true"
21. android:layout_alignParentTop="true" />
22.
23.
24. <ScrollView android:layout_marginTop="30dp"
25. android:layout_width="fill_parent"
26. android:layout_height="wrap_content"
27. android:id="@+id/scrollView">
28.
29.
30. <LinearLayout
31. android:layout_width="fill_parent"
32. android:layout_height="fill_parent"
33. android:orientation="vertical" >
34.
35. <Button
36. android:layout_width="fill_parent"
37. android:layout_height="wrap_content"
38. android:text="Button 1" />
39. <Button
40. android:layout_width="fill_parent"
41. android:layout_height="wrap_content"
42. android:text="Button 2" />
43. <Button
44. android:layout_width="fill_parent"
45. android:layout_height="wrap_content"
46. android:text="Button 3" />
47. <Button
48. android:layout_width="fill_parent"
49. android:layout_height="wrap_content"
50. android:text="Button 4" />
51. <Button
52. android:layout_width="fill_parent"
53. android:layout_height="wrap_content"
54. android:text="Button 5" />
55. <Button
56. android:layout_width="fill_parent"
57. android:layout_height="wrap_content"
58. android:text="Button 6" />
59. <Button
60. android:layout_width="fill_parent"
61. android:layout_height="wrap_content"
62. android:text="Button 7" />
63. <Button
64. android:layout_width="fill_parent"
65. android:layout_height="wrap_content"
66. android:text="Button 8" />
67. <Button
68. android:layout_width="fill_parent"
69. android:layout_height="wrap_content"
70. android:text="Button 9" />
71. <Button
72. android:layout_width="fill_parent"
73. android:layout_height="wrap_content"
74. android:text="Button 10" />
75. <Button
76. android:layout_width="fill_parent"
77. android:layout_height="wrap_content"
78. android:text="Button 11" />
79. <Button
80. android:layout_width="fill_parent"
81. android:layout_height="wrap_content"
82. android:text="Button 12" />
83. <Button
84. android:layout_width="fill_parent"
85. android:layout_height="wrap_content"
86. android:text="Button 13" />
87. <Button
88. android:layout_width="fill_parent"
89. android:layout_height="wrap_content"
90. android:text="Button 14" />
91. <Button
92. android:layout_width="fill_parent"
93. android:layout_height="wrap_content"
94. android:text="Button 15" />
95. <Button
96. android:layout_width="fill_parent"
97. android:layout_height="wrap_content"
98. android:text="Button 16" />
99. <Button
100. android:layout_width="fill_parent"
101. android:layout_height="wrap_content"
102. android:text="Button 17" />
103. <Button
104. android:layout_width="fill_parent"
105. android:layout_height="wrap_content"
106. android:text="Button 18" />
107.
108. <Button
109. android:layout_width="fill_parent"
110. android:layout_height="wrap_content"
111. android:text="Button 19" />
112. <Button
113. android:layout_width="fill_parent"
114. android:layout_height="wrap_content"
115. android:text="Button 20" />
116.
117. </LinearLayout>
118.
119. </ScrollView>
120.
121. </RelativeLayout>
Activity class
In activity class, we have not changed any code.
File: MainActivity.java
1. package com.example.test.scrollviews;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_main);
12. }
13. }
Output
Android HorizontalScrollView
A HorizontalScrollView is a FrameLayout.
The android.widget.HorizontalScrollView class provides the functionality of
horizontal scroll view. HorizontalScrollView is used to scroll the child elements or
views in a horizontal direction. HorizontalScrollView only supports horizontal
scrolling.
activity_main.xml
Now, drag HorizontalScrollView from palette to activity_main.xml file and place some
views or elements inside it.
File: MainActivity.java
1. package com.example.test.horizantalscrollview;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_main);
12. }
13. }
Android Image Switcher
Android image switcher provides an animation over images to transition from one
image to another. In order to use image switcher, we need to
implement ImageSwitcher component in .xml file.
activity_main.xml
File: activity_main.xml
1. package com.example.test.imageswitcher;
2.
3. import android.os.Bundle;
4. import android.support.v7.app.AppCompatActivity;
5. import android.support.v7.widget.Toolbar;
6. import android.view.View;
7. import android.widget.Button;
8. import android.widget.ImageSwitcher;
9. import android.widget.ImageView;
10. import android.widget.ViewSwitcher;
11.
12. import android.app.ActionBar;
13. import android.view.animation.Animation;
14. import android.view.animation.AnimationUtils;
15.
16.
17. public class MainActivity extends AppCompatActivity {
18. ImageSwitcher imageSwitcher;
19. Button nextButton;
20.
21. int imageSwitcherImages[] =
22. {R.drawable.cpp, R.drawable.c_sarp, R.drawable.jsp, R.drawable.mysql, R.drawable.
hadoop};
23.
24. int switcherImageLength = imageSwitcherImages.length;
25. int counter = -1;
26.
27. @Override
28. protected void onCreate(Bundle savedInstanceState) {
29. super.onCreate(savedInstanceState);
30. setContentView(R.layout.activity_main);
31. Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
32. setSupportActionBar(toolbar);
33.
34. imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
35. nextButton = (Button) findViewById(R.id.button);
36.
37. imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
38. @Override
39. public View makeView() {
40. ImageView switcherImageView = new ImageView(getApplicationContext());
Output
Android Image Slider
Android image slider slides one entire screen to another screen. Image slider is
created by ViewPager which is provided by support library. To implement image
slider, you need to inherit ViewPager class which extends PagerAdapter.
activity_main.xml
In activity_main.xml file, we have wrapped ViewPager inside RelativeLayout.
File: activity_main.xml
File: ImageAdapter.java
1. package com.example.test.imageslider;
2.
3. import android.content.Context;
4. import android.support.v4.view.PagerAdapter;
5. import android.support.v4.view.ViewPager;
6. import android.view.View;
7. import android.view.ViewGroup;
8. import android.widget.ImageView;
9.
10. public class ImageAdapter extends PagerAdapter{
11. Context mContext;
12.
13. ImageAdapter(Context context) {
14. this.mContext = context;
15. }
16.
17. @Override
18. public boolean isViewFromObject(View view, Object object) {
19. return view == ((ImageView) object);
20. }
21.
22. private int[] sliderImageId = new int[]{
23. R.drawable.image1, R.drawable.image2, R.drawable.image3,R.drawable.
image4, R.drawable.image5,
24. };
25.
26. @Override
27. public Object instantiateItem(ViewGroup container, int position) {
28. ImageView imageView = new ImageView(mContext);
29. imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
30. imageView.setImageResource(sliderImageId[position]);
31. ((ViewPager) container).addView(imageView, 0);
32. return imageView;
33. }
34.
35. @Override
36. public void destroyItem(ViewGroup container, int position, Object object) {
37. ((ViewPager) container).removeView((ImageView) object);
38. }
39.
40. @Override
41. public int getCount() {
42. return sliderImageId.length;
43. }
44. }
Output
Android ViewStub
A ViewStub is a zero-sized invisible View which is used to load "layout resource" at
runtime. ViewStub is a zero dimension View, so you will not see anything on the
layout pallete.
Example of ViewStub
Let's create an example of ViewStub View that displays and hides an ImageView
(image) created in another layout (my_layout.xml) file.
File: activity.xml
File: my_layout.xml
1. package com.example.test.viewstubexample;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.View;
6. import android.view.ViewStub;
7. import android.widget.Button;
8.
9. public class MainActivity extends AppCompatActivity {
10. ViewStub viewStub;
11. Button show,hide;
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16.
17. show=(Button)findViewById(R.id.show);
18. hide=(Button)findViewById(R.id.hide);
19. viewStub=(ViewStub)findViewById(R.id.viewStub);
20. viewStub.inflate();
21.
22. show.setOnClickListener(new View.OnClickListener() {
23. @Override
24. public void onClick(View v) {
25. viewStub.setVisibility(View.VISIBLE);
26. }
27. });
28. hide.setOnClickListener(new View.OnClickListener() {
29. @Override
30. public void onClick(View v) {
31. viewStub.setVisibility(View.GONE);
32. }
33. });
34. }
35. }
Output
Android TabLayout
TabLayout is used to implement horizontal tabs. TabLayout is released by Android
after the deprecation of ActionBar.TabListener (API level 21).
Tabs are created using newTab() method of TabLayout class. The title and icon of
Tabs are set through setText(int) and setIcon(int) methods of TabListener interface
respectively. Tabs of layout are attached over TabLayout using the method
addTab(Tab) method.
We can also add tab item to TabLayout using TabItem of android design widget.
1. <android.support.design.widget.TabItem
2. android:text="@string/tab_text"/>
Example of TabLayout using ViewPager
Let's create an example of TabLayout using ViewPager and Fragment.
File: activity.xml
File: build.gradle
1. implementation 'com.android.support:design:26.1.0'
File: MainActivity.java
1. package tablayout.example.com.tablayout;
2.
3. import android.support.design.widget.TabLayout;
4. import android.support.v4.view.ViewPager;
5. import android.support.v7.app.AppCompatActivity;
6. import android.os.Bundle;
7.
8. public class MainActivity extends AppCompatActivity {
9. TabLayout tabLayout;
10. ViewPager viewPager;
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_main);
15.
16. tabLayout=(TabLayout)findViewById(R.id.tabLayout);
17. viewPager=(ViewPager)findViewById(R.id.viewPager);
18.
19. tabLayout.addTab(tabLayout.newTab().setText("Home"));
20. tabLayout.addTab(tabLayout.newTab().setText("Sport"));
21. tabLayout.addTab(tabLayout.newTab().setText("Movie"));
22. tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
23.
24. final MyAdapter adapter = new MyAdapter(this,getSupportFragmentManager(),
tabLayout.getTabCount());
25. viewPager.setAdapter(adapter);
26.
27. viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPage
ChangeListener(tabLayout));
28.
29. tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedList
ener() {
30. @Override
31. public void onTabSelected(TabLayout.Tab tab) {
32. viewPager.setCurrentItem(tab.getPosition());
33. }
34.
35. @Override
36. public void onTabUnselected(TabLayout.Tab tab) {
37.
38. }
39.
40. @Override
41. public void onTabReselected(TabLayout.Tab tab) {
42.
43. }
44. });
45.
46. }
47. }
File: MyAdapter.java
1. package tablayout.example.com.tablayout;
2.
3. import android.content.Context;
4. import android.support.v4.app.Fragment;
5. import android.support.v4.app.FragmentPagerAdapter;
6. import android.support.v4.app.FragmentManager;
7.
8. public class MyAdapter extends FragmentPagerAdapter {
9.
10. private Context myContext;
11. int totalTabs;
12.
13. public MyAdapter(Context context, FragmentManager fm, int totalTabs) {
14. super(fm);
15. myContext = context;
16. this.totalTabs = totalTabs;
17. }
18.
19. // this is for fragment tabs
20. @Override
21. public Fragment getItem(int position) {
22. switch (position) {
23. case 0:
24. HomeFragment homeFragment = new HomeFragment();
25. return homeFragment;
26. case 1:
27. SportFragment sportFragment = new SportFragment();
28. return sportFragment;
29. case 2:
30. MovieFragment movieFragment = new MovieFragment();
31. return movieFragment;
32. default:
33. return null;
34. }
35. }
36. // this counts total number of tabs
37. @Override
38. public int getCount() {
39. return totalTabs;
40. }
41. }
File: HomeFragment.java
1. package tablayout.example.com.tablayout;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class HomeFragment extends Fragment {
10.
11.
12. public HomeFragment() {
13. // Required empty public constructor
14. }
15.
16. @Override
17. public View onCreateView(LayoutInflater inflater, ViewGroup container,
18. Bundle savedInstanceState) {
19. // Inflate the layout for this fragment
20. return inflater.inflate(R.layout.fragment_home, container, false);
21. }
22.
23. }
File: fragment_home.xml
1. <FrameLayout 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="tablayout.example.com.tablayout.HomeFragment">
6.
7. <!-- TODO: Update blank fragment layout -->
8.
9. <TextView
10. android:layout_width="match_parent"
11. android:layout_height="match_parent"
12. android:gravity="center"
13. android:text="@string/home_fragment" />
14.
15. </FrameLayout>
File: SportFragment.java
1. package tablayout.example.com.tablayout;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class SportFragment extends Fragment {
10.
11.
12. public SportFragment() {
13. // Required empty public constructor
14. }
15.
16. @Override
17. public View onCreateView(LayoutInflater inflater, ViewGroup container,
18. Bundle savedInstanceState) {
19. // Inflate the layout for this fragment
20. return inflater.inflate(R.layout.fragment_sport, container, false);
21. }
22.
23. }
File: fragment_sport.xml
1. <FrameLayout 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="tablayout.example.com.tablayout.SportFragment">
6.
7. <!-- TODO: Update blank fragment layout -->
8. <TextView
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. android:gravity="center"
12. android:text="@string/sport_fragment" />
13.
14. </FrameLayout>
File: MovieFragment.java
1. package tablayout.example.com.tablayout;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class MovieFragment extends Fragment {
10.
11.
12. public MovieFragment() {
13. // Required empty public constructor
14. }
15.
16. @Override
17. public View onCreateView(LayoutInflater inflater, ViewGroup container,
18. Bundle savedInstanceState) {
19. // Inflate the layout for this fragment
20. return inflater.inflate(R.layout.fragment_movie, container, false);
21. }
22.
23. }
File: fragment_movie.xml
1. <FrameLayout 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="tablayout.example.com.tablayout.MovieFragment">
6.
7. <!-- TODO: Update blank fragment layout -->
8. <TextView
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. android:gravity="center"
12. android:text="@string/movie_fragment" />
13.
14. </FrameLayout>
File: strings.xml
1. <resources>
2. <string name="app_name">TabLayout</string>
3.
4. <!-- TODO: Remove or change this placeholder text -->
5. <string name="home_fragment">Home Fragment</string>
6. <string name="sport_fragment">Sport Fragment</string>
7. <string name="movie_fragment">Movie Fragment</string>
8.
9. </resources>
Output
Android TabLayout with FrameLayout
In the previous page, we created a sliding tabs using TabLayout and ViewPager. Here,
we are going to create non sliding tabs using TabLayout and FrameLayout.
File: activity.xml
File: build.gradle
1. implementation 'com.android.support:design:26.1.0'
File: MainActivity.java
1. package tablayout.example.com.tablayoutwithframelayout;
2.
3. import android.support.design.widget.TabLayout;
4. import android.support.v4.app.Fragment;
5. import android.support.v4.app.FragmentManager;
6. import android.support.v4.app.FragmentTransaction;
7. import android.support.v7.app.AppCompatActivity;
8. import android.os.Bundle;
9. import android.widget.FrameLayout;
10.
11. public class MainActivity extends AppCompatActivity {
12. TabLayout tabLayout;
13. FrameLayout frameLayout;
14. Fragment fragment = null;
15. FragmentManager fragmentManager;
16. FragmentTransaction fragmentTransaction;
17. @Override
18. protected void onCreate(Bundle savedInstanceState) {
19. super.onCreate(savedInstanceState);
20. setContentView(R.layout.activity_main);
21.
22. tabLayout=(TabLayout)findViewById(R.id.tabLayout);
23. frameLayout=(FrameLayout)findViewById(R.id.frameLayout);
24.
25. fragment = new HomeFragment();
26. fragmentManager = getSupportFragmentManager();
27. fragmentTransaction = fragmentManager.beginTransaction();
28. fragmentTransaction.replace(R.id.frameLayout, fragment);
29. fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGM
ENT_OPEN);
30. fragmentTransaction.commit();
31.
32. tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
33. @Override
34. public void onTabSelected(TabLayout.Tab tab) {
35. // Fragment fragment = null;
36. switch (tab.getPosition()) {
37. case 0:
38. fragment = new HomeFragment();
39. break;
40. case 1:
41. fragment = new JavaFragment();
42. break;
43. case 2:
44. fragment = new AndroidFragment();
45. break;
46. case 3:
47. fragment = new PhpFragment();
48. break;
49. }
50. FragmentManager fm = getSupportFragmentManager();
51. FragmentTransaction ft = fm.beginTransaction();
52. ft.replace(R.id.frameLayout, fragment);
53. ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
54. ft.commit();
55. }
56.
57. @Override
58. public void onTabUnselected(TabLayout.Tab tab) {
59.
60. }
61.
62. @Override
63. public void onTabReselected(TabLayout.Tab tab) {
64.
65. }
66. });
67.
68. }
69. }
File: HomeFragment.java
1. package tablayout.example.com.tablayoutwithframelayout;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class HomeFragment extends Fragment {
10.
11. public HomeFragment() {
12. // Required empty public constructor
13. }
14.
15. @Override
16. public View onCreateView(LayoutInflater inflater, ViewGroup container,
17. Bundle savedInstanceState) {
18. // Inflate the layout for this fragment
19. return inflater.inflate(R.layout.fragment_home, container, false);
20. }
21.
22. }
File: fragment_home.xml
1. <FrameLayout 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="tablayout.example.com.tablayoutwithframelayout.HomeFrag
ment">
6.
7. <!-- TODO: Update blank fragment layout -->
8. <TextView
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. android:gravity="center"
12. android:text="@string/home_fragment" />
13.
14. </FrameLayout>
File: JavaFragment.java
1. package tablayout.example.com.tablayoutwithframelayout;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class JavaFragment extends Fragment {
10.
11. public JavaFragment() {
12. // Required empty public constructor
13. }
14.
15. @Override
16. public View onCreateView(LayoutInflater inflater, ViewGroup container,
17. Bundle savedInstanceState) {
18. // Inflate the layout for this fragment
19. return inflater.inflate(R.layout.fragment_java, container, false);
20. }
21.
22. }
File: fragment_java.xml
1. <FrameLayout 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="tablayout.example.com.tablayoutwithframelayout.JavaFragm
ent">
6.
7. <!-- TODO: Update blank fragment layout -->
8. <TextView
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. android:gravity="center"
12. android:text="@string/java_fragment" />
13.
14. </FrameLayout>
File: AndroidFragment.java
1. package tablayout.example.com.tablayoutwithframelayout;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class AndroidFragment extends Fragment {
10.
11. public AndroidFragment() {
12. // Required empty public constructor
13. }
14.
15. @Override
16. public View onCreateView(LayoutInflater inflater, ViewGroup container,
17. Bundle savedInstanceState) {
18. // Inflate the layout for this fragment
19. return inflater.inflate(R.layout.fragment_android, container, false);
20. }
21.
22. }
File: fragment_android.xml
1. <FrameLayout 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="tablayout.example.com.tablayoutwithframelayout.AndroidFr
agment">
6.
7. <!-- TODO: Update blank fragment layout -->
8. <TextView
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. android:gravity="center"
12. android:text="@string/android_fragment" />
13.
14. </FrameLayout>
File: PhpFragment.java
1. package tablayout.example.com.tablayoutwithframelayout;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class PhpFragment extends Fragment {
10.
11. public PhpFragment() {
12. // Required empty public constructor
13. }
14.
15. @Override
16. public View onCreateView(LayoutInflater inflater, ViewGroup container,
17. Bundle savedInstanceState) {
18. // Inflate the layout for this fragment
19. return inflater.inflate(R.layout.fragment_php, container, false);
20. }
21.
22. }
File: fragment_php.xml
1. <FrameLayout 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="tablayout.example.com.tablayoutwithframelayout.PhpFragm
ent">
6.
7. <!-- TODO: Update blank fragment layout -->
8. <TextView
9. android:layout_width="match_parent"
10. android:layout_height="match_parent"
11. android:gravity="center"
12. android:text="@string/php_fragment" />
13.
14. </FrameLayout>
File: strings.xml
1. <resources>
2. <string name="app_name">TabLayout with FrameLayout</string>
3.
4. <!-- TODO: Remove or change this placeholder text -->
5. <string name="home_fragment">Home fragment</string>
6. <string name="java_fragment">Java fragment</string>
7. <string name="android_fragment">Android fragment</string>
8. <string name="php_fragment">Php fragment</string>
9. </resources>
Output
Android SearchView
Android SearchView provides user interface to search query submitted over search
provider. SearchView widget can be implemented over ToolBar/ActionBar or inside a
layout.
Methods of SearchView
1. public boolean onQueryTextSubmit(String query): It searches the query on the
submission of content over SearchView editor. It is case dependent.
2. public boolean onQueryTextChange(String newText): It searches the query at the
time of text change over SearchView editor.
Example of SearchView
Let's see the example of SearchView over layout, searching data in a ListView.
activity_main.xml
Create an activity_main.xml file in layout folder containing ScrollView and ListView.
File: activity_main.xml
1. package com.example.test.searchview;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.widget.ArrayAdapter;
6. import android.widget.Filter;
7. import android.widget.ListView;
8. import android.widget.SearchView;
9. import android.widget.Toast;
10.
11. import java.util.ArrayList;
12.
13. public class MainActivity extends AppCompatActivity {
14. SearchView searchView;
15. ListView listView;
16. ArrayList<String> list;
17. ArrayAdapter<String > adapter;
18. @Override
19. protected void onCreate(Bundle savedInstanceState) {
20. super.onCreate(savedInstanceState);
21. setContentView(R.layout.activity_main);
22.
23. searchView = (SearchView) findViewById(R.id.searchView);
24. listView = (ListView) findViewById(R.id.lv1);
25.
26. list = new ArrayList<>();
27. list.add("Apple");
28. list.add("Banana");
29. list.add("Pineapple");
30. list.add("Orange");
31. list.add("Lychee");
32. list.add("Gavava");
33. list.add("Peech");
34. list.add("Melon");
35. list.add("Watermelon");
36. list.add("Papaya");
37.
38. adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,lis
t);
39. listView.setAdapter(adapter);
40.
41. searchView.setOnQueryTextListener(new SearchView.OnQueryTextListen
er() {
42. @Override
43. public boolean onQueryTextSubmit(String query) {
44.
45. if(list.contains(query)){
46. adapter.getFilter().filter(query);
47. }else{
48. Toast.makeText(MainActivity.this, "No Match found",Toast.LENGTH_LONG
).show();
49. }
50. return false;
51. }
52.
53. @Override
54. public boolean onQueryTextChange(String newText) {
55. // adapter.getFilter().filter(newText);
56. return false;
57. }
58. });
59. }
60. }
Output
Android SearchView on ToolBar
As we have already implemented SearchView widget over activity layout, it can also
be implemented over ToolBar/ActionBar. For implementing SearchView over ToolBar,
we need to create menu option and place SearchView widget on it.
activity_main.xml
Create an activity_main.xml file in layout folder containing ListView.
File: activity_main.xml
File: menu.xml
1. package searchview.toolbar.com.searchviewtoolbar;
2.
3. import android.support.v4.view.MenuItemCompat;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.Menu;
7. import android.view.MenuInflater;
8. import android.view.MenuItem;
9. import android.widget.ArrayAdapter;
10. import android.widget.ListView;
11. import android.widget.SearchView;
12. import android.widget.Toast;
13.
14. import java.util.ArrayList;
15.
16. public class MainActivity extends AppCompatActivity {
17.
18. ListView listView;
19. ArrayList<String> list;
20. ArrayAdapter<String > adapter;
21. @Override
22. protected void onCreate(Bundle savedInstanceState) {
23. super.onCreate(savedInstanceState);
24. setContentView(R.layout.activity_main);
25.
26. listView = (ListView) findViewById(R.id.listView);
27.
28. list = new ArrayList<>();
29. list.add("Apple");
30. list.add("Banana");
31. list.add("Pineapple");
32. list.add("Orange");
33. list.add("Lychee");
34. list.add("Gavava");
35. list.add("Peech");
36. list.add("Melon");
37. list.add("Watermelon");
38. list.add("Papaya");
39.
40. adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,lis
t);
41. listView.setAdapter(adapter);
42. }
43.
44. @Override
45. public boolean onCreateOptionsMenu(Menu menu) {
46. MenuInflater inflater = getMenuInflater();
47. inflater.inflate(R.menu.menu, menu);
48. MenuItem searchViewItem = menu.findItem(R.id.app_bar_search);
49. final SearchView searchView = (SearchView) MenuItemCompat.getAction
View(searchViewItem);
50. searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
51. @Override
52. public boolean onQueryTextSubmit(String query) {
53. searchView.clearFocus();
54. /* if(list.contains(query)){
55. adapter.getFilter().filter(query);
56. }else{
57. Toast.makeText(MainActivity.this, "No Match found",Toast.LENGT
H_LONG).show();
58. }*/
59. return false;
60.
61. }
62.
63. @Override
64. public boolean onQueryTextChange(String newText) {
65. adapter.getFilter().filter(newText);
66. return false;
67. }
68. });
69. return super.onCreateOptionsMenu(menu);
70. }
71. }
Output
Android EditText with TextWatcher
(Searching data from ListView)
Android EditText is a subclass of TextView. EditText is used for entering and
modifying text. While using EditText width, we must specify its input type
in inputType property of EditText which configures the keyboard according to input.
EditText uses TextWatcher interface to watch change made over EditText. For doing
this, EditText calls the addTextChangedListener() method.
Methods of TextWatcher
1. beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3): It is
executed before making any change over EditText.
2. onTextChanged(CharSequence cs, int arg1, int arg2, int arg3): It is executed while
making any change over EditText.
3. afterTextChanged(Editable arg0): It is executed after change made over EditText.
Example of EditText with TextWatcher()
In this example, we will implement EditText with TextWatcher to search data from
ListView.
activity_main.xml
Create an activity_main.xml file in layout folder containing EditText and ListView.
File: activity_main.xml
Create another file list_item.xml in layout folder which contains data of ListView.
list_item.xm
File: list_item.xml
1. package com.example.test.searchfromlistview;
2.
3. import android.os.Bundle;
4. import android.text.Editable;
5. import android.text.TextWatcher;
6. import android.widget.ArrayAdapter;
7. import android.widget.EditText;
8. import android.widget.ListView;
9. import android.support.v7.app.AppCompatActivity;
10. import android.widget.Toast;
11.
12. public class MainActivity extends AppCompatActivity {
13.
14. private ListView lv;
15. private EditText editText;
16. private ArrayAdapter<String> adapter;
17.
18. private String products[] = {"Apple", "Banana","Pinapple", "Orange", "Papaya", "Mel
on",
19. "Grapes", "Water Melon","Lychee", "Guava", "Mango", "Kivi"};
20. @Override
21. protected void onCreate(Bundle savedInstanceState) {
22. super.onCreate(savedInstanceState);
23. setContentView(R.layout.activity_main);
24.
25. lv = (ListView) findViewById(R.id.listView);
26. editText = (EditText) findViewById(R.id.editText);
27. adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.produc
t_name, products);
28. lv.setAdapter(adapter);
29.
30. editText.addTextChangedListener(new TextWatcher() {
31.
32. @Override
33. public void onTextChanged(CharSequence cs, int arg1, int arg2, int ar
g3) {
34. adapter.getFilter().filter(cs);
35. }
36.
37. @Override
38. public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg
3) {
39. Toast.makeText(getApplicationContext(),"before text change",Toast.
LENGTH_LONG).show();
40. }
41.
42. @Override
43. public void afterTextChanged(Editable arg0) {
44. Toast.makeText(getApplicationContext(),"after text change",Toast.LENGTH_L
ONG).show();
45. }
46. });
47. }
48. }
Output
Android Activity Lifecycle
By the help of activity, you can place all your UI components or widgets in a single
screen.
The 7 lifecycle method of Activity describes how activity will behave at different
states.
Method Description
onResume called when activity will start interacting with the user.
File: activity_main.xml
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.
Now see on the logcat: onCreate, onStart and onResume methods are invoked.
Now click on the HOME Button. You will see onPause method is invoked.
After a while, you will see onStop method is invoked.
Now see on the emulator. It is on the home. Now click on the center button to
launch the app again.
Now click on the lifecycleactivity icon.
Now see on the logcat: onRestart, onStart and onResume methods are invoked.
After a while, you will see onStop and onDestroy methods are invoked.
The onCreate() and onDestroy() methods are called only once throughout the
activity lifecycle.
Android Intent is the message that is passed between components such as activities,
content providers, broadcast receivers, services etc.
1) Implicit Intent
Implicit Intent doesn't specifiy the component. In such case, intent provides
information of available components provided by the system that is to be invoked.
For example, you may write the following code to view the webpage.
To get the full code of explicit intent, visit the next page.
activity_main.xml
File: activity_main.xml
Activity class
File: MainActivity.java
1. package example.javatpoint.com.implicitintent;
2.
3. import android.content.Intent;
4. import android.net.Uri;
5. import android.support.v7.app.AppCompatActivity;
6. import android.os.Bundle;
7. import android.view.View;
8. import android.widget.Button;
9. import android.widget.EditText;
10.
11. public class MainActivity extends AppCompatActivity {
12.
13. Button button;
14. EditText editText;
15.
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_main);
20.
21. button = findViewById(R.id.button);
22. editText = findViewById(R.id.editText);
23.
24. button.setOnClickListener(new View.OnClickListener() {
25. @Override
26. public void onClick(View view) {
27. String url=editText.getText().toString();
28. Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(url));
29. startActivity(intent);
30. }
31. });
32. }
33. }
Output:
Android Explicit Intent Example
Android Explicit intent specifies the component to be invoked from activity. In
other words, we can call another activity in android by explicit intent.
We can also pass the information from one activity to another using explicit intent.
Here, we are going to see an example to call one activity from another and vice-
versa.
1. package example.javatpoint.com.explicitintent;
2.
3. import android.content.Intent;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7.
8. public class FirstActivity extends AppCompatActivity {
9.
10. @Override
11. protected void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. setContentView(R.layout.activity_first);
14. }
15. public void callSecondActivity(View view){
16. Intent i = new Intent(getApplicationContext(), SecondActivity.class);
17. i.putExtra("Value1", "Android By Javatpoint");
18. i.putExtra("Value2", "Simple Tutorial");
19. // Set the request code to any code you like, you can identify the
20. // callback via this code
21. startActivity(i);
22. }
23.
24. }
activitytwo_main.xml
File: activitytwo_main.xml
Method Signature
There are two variants of startActivityForResult() method.
1. public void startActivityForResult (Intent intent, int requestCode)
2. public void startActivityForResult (Intent intent, int requestCode, Bundle options)
activity_main.xml
Drag one textview and one button from the pallete, now the xml file will look like
this.
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10. <TextView
11. android:id="@+id/textView1"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:layout_alignLeft="@+id/button1"
15. android:layout_alignParentTop="true"
16. android:layout_marginTop="48dp"
17. android:text="Default Message" />
18. <Button
19. android:id="@+id/button1"
20. android:layout_width="wrap_content"
21. android:layout_height="wrap_content"
22. android:layout_below="@+id/textView1"
23. android:layout_centerHorizontal="true"
24. android:layout_marginTop="42dp"
25. android:text="GetMessage" />
26. </RelativeLayout>
second_main.xml
This xml file is created automatically when you create another activity. To create new
activity Right click on the package inside the src -> New -> Other ->Android
Activity.
Now drag one editText, one textView and one button from the pallete, now the xml
file will look like this:
File: second_main.xml
1. <RelativeLayout xmlns:androclass="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. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".SecondActivity" >
10. <EditText
11. android:id="@+id/editText1"
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:layout_alignParentTop="true"
15. android:layout_marginTop="61dp"
16. android:layout_toRightOf="@+id/textView1"
17. android:ems="10" />
18. <TextView
19. android:id="@+id/textView1"
20. android:layout_width="wrap_content"
21. android:layout_height="wrap_content"
22. android:layout_alignBaseline="@+id/editText1"
23. android:layout_alignBottom="@+id/editText1"
24. android:layout_alignParentLeft="true"
25. android:text="Enter Message:" />
26. <Button
27. android:id="@+id/button1"
28. android:layout_width="wrap_content"
29. android:layout_height="wrap_content"
30. android:layout_below="@+id/editText1"
31. android:layout_centerHorizontal="true"
32. android:layout_marginTop="34dp"
33. android:text="Submit" />
34. </RelativeLayout>
Activity class
Now let's write the code that invokes another activity and get result from that
activity.
File: MainActivity.java
1. package com.javatpoint.startactivityforresult;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.content.Intent;
5. import android.view.Menu;
6. import android.view.View;
7. import android.view.View.OnClickListener;
8. import android.widget.Button;
9. import android.widget.TextView;
10. public class MainActivity extends Activity {
11. TextView textView1;
12. Button button1;
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17. textView1=(TextView)findViewById(R.id.textView1);
18. button1=(Button)findViewById(R.id.button1);
19. button1.setOnClickListener(new OnClickListener() {
20. @Override
21. public void onClick(View arg0) {
22. Intent intent=new Intent(MainActivity.this,SecondActivity.class);
23. startActivityForResult(intent, 2);// Activity is started with requestCod
e2
24. }
25. });
26. }
27. // Call Back method to get the Message form other Activity
28. @Override
29. protected void onActivityResult(int requestCode, int resultCode, Intent d
ata)
30. {
31. super.onActivityResult(requestCode, resultCode, data);
32. // check if the request code is same as what is passed here it is 2
33. if(requestCode==2)
34. {
35. String message=data.getStringExtra("MESSAGE");
36. textView1.setText(message);
37. }
38. }
39. @Override
40. public boolean onCreateOptionsMenu(Menu menu) {
41. // Inflate the menu; this adds items to the action bar if it is present.
42. getMenuInflater().inflate(R.menu.main, menu);
43. return true;
44. }
45. }
SecondActivity class
Let's write the code that displays the content of second activity layout file.
File: SecondActivity.java
1. package com.javatpoint.startactivityforresult;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.content.Intent;
5. import android.view.Menu;
6. import android.view.View;
7. import android.view.View.OnClickListener;
8. import android.widget.Button;
9. import android.widget.EditText;
10. import android.widget.TextView;
11. public class SecondActivity extends Activity {
12. EditText editText1;
13. Button button1;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_second);
18. editText1=(EditText)findViewById(R.id.editText1);
19. button1=(Button)findViewById(R.id.button1);
20. button1.setOnClickListener(new OnClickListener() {
21. @Override
22. public void onClick(View arg0) {
23. String message=editText1.getText().toString();
24. Intent intent=new Intent();
25. intent.putExtra("MESSAGE",message);
26. setResult(2,intent);
27. finish();//finishing activity
28. }
29. });
30. }
31. @Override
32. public boolean onCreateOptionsMenu(Menu menu) {
33. // Inflate the menu; this adds items to the action bar if it is present.
34. getMenuInflater().inflate(R.menu.second, menu);
35. return true;
36. }
37. }
Example of ACTION_SEND
In this example, we are going to share plain text which is a URL of browser.
activity_main.xml
File: activity_main.xml
1. package com.example.test.shareapp;
2.
3. import android.content.Intent;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.widget.Button;
8.
9. public class MainActivity extends AppCompatActivity {
10. Button sharebutton;
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_main);
15.
16. sharebutton=(Button)findViewById(R.id.button);
17. sharebutton.setOnClickListener(new View.OnClickListener() {
18. @Override
19. public void onClick(View v) {
20. Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
21. shareIntent.setType("text/plain");
22. shareIntent.putExtra(Intent.EXTRA_SUBJECT,"Insert Subject here");
23. String app_url = " https://play.google.com/store/apps/details?
id=my.example.javatpoint";
24. shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,app_url);
25. startActivity(Intent.createChooser(shareIntent, "Share via"));
26. }
27. });
28. }
29. }
Output
Android Fragments
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.
Each fragment has its own life cycle methods that is affected by activity life cycle
because fragments are embedded in activity.
activity_main.xml
File: activity_main.xml
1. <FrameLayout 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. android:background="#F5F5DC"
6. tools:context="example.javatpoint.com.fragmentexample.Fragment1">
7.
8. <!-- TODO: Update blank fragment layout -->
9. <TextView
10. android:layout_width="match_parent"
11. android:layout_height="match_parent"
12. android:text="@string/hello_blank_fragment" />
13.
14. </FrameLayout>
File: fragment_fragment2.xml
1. <FrameLayout 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. android:background="#F0FFFF"
6. tools:context="example.javatpoint.com.fragmentexample.Fragment2">
7.
8. <!-- TODO: Update blank fragment layout -->
9. <TextView
10. android:layout_width="match_parent"
11. android:layout_height="match_parent"
12. android:text="@string/hello_blank_fragment" />
13.
14. </FrameLayout>
MainActivity class
File: MainActivity.java
1. package example.javatpoint.com.fragmentexample;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_main);
12. }
13. }
File: Fragment1.java
1. package example.javatpoint.com.fragmentexample;
2. import android.os.Bundle;
3. import android.support.v4.app.Fragment;
4. import android.view.LayoutInflater;
5. import android.view.View;
6. import android.view.ViewGroup;
7.
8. public class Fragment1 extends Fragment {
9.
10. @Override
11. public void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. }
14.
15. @Override
16. public View onCreateView(LayoutInflater inflater, ViewGroup container,
17. Bundle savedInstanceState) {
18. // Inflate the layout for this fragment
19. return inflater.inflate(R.layout.fragment_fragment1, container, false);
20. }
21. }
File: Fragment2.java
1. package example.javatpoint.com.fragmentexample;
2.
3. import android.os.Bundle;
4. import android.support.v4.app.Fragment;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class Fragment2 extends Fragment {
10.
11. @Override
12. public void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. }
15.
16. @Override
17. public View onCreateView(LayoutInflater inflater, ViewGroup container,
18. Bundle savedInstanceState) {
19. // Inflate the layout for this fragment
20. return inflater.inflate(R.layout.fragment_fragment2, container, false);
21. }
22.
23. }
Output:
Here, we are going to see two examples of option menus. First, the simple option
menus and second, options menus with images.
File: activity_main.xml
It contains three items as show below. It is created automatically inside the res/menu
directory.
File: menu_main.xml
1. <menu xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:app="http://schemas.android.com/apk/res-auto"
3. xmlns:tools="http://schemas.android.com/tools"
4. tools:context="example.javatpoint.com.optionmenu.MainActivity">
5.
6. <item android:id="@+id/item1"
7. android:title="Item 1"/>
8. <item android:id="@+id/item2"
9. android:title="Item 2"/>
10. <item android:id="@+id/item3"
11. android:title="Item 3"
12. app:showAsAction="withText"/>
13. </menu>
Activity class
This class displays the content of menu.xml file and performs event handling on
clicking the menu items.
File: MainActivity.java
1. package example.javatpoint.com.optionmenu;
2.
3. import android.os.Bundle;
4. import android.support.v7.app.AppCompatActivity;
5. import android.support.v7.widget.Toolbar;
6. import android.view.Menu;
7. import android.view.MenuItem;
8. import android.widget.Toast;
9.
10. public class MainActivity extends AppCompatActivity {
11.
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16. Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
17. setSupportActionBar(toolbar);
18. }
19.
20. @Override
21. public boolean onCreateOptionsMenu(Menu menu) {
22. // Inflate the menu; this adds items to the action bar if it is present.
23. getMenuInflater().inflate(R.menu.menu_main, menu);
24. return true;
25. }
26.
27. @Override
28. public boolean onOptionsItemSelected(MenuItem item) {
29. int id = item.getItemId();
30. switch (id){
31. case R.id.item1:
32. Toast.makeText(getApplicationContext(),"Item 1 Selected",Toast.LENGTH_LO
NG).show();
33. return true;
34. case R.id.item2:
35. Toast.makeText(getApplicationContext(),"Item 2 Selected",Toast.LEN
GTH_LONG).show();
36. return true;
37. case R.id.item3:
38. Toast.makeText(getApplicationContext(),"Item 3 Selected",Toast.LENGTH_LO
NG).show();
39. return true;
40. default:
41. return super.onOptionsItemSelected(item);
42. }
43. }
44. }
Output:
File: menu_main.xml
1. <menu xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:app="http://schemas.android.com/apk/res-auto"
3. xmlns:tools="http://schemas.android.com/tools"
4. tools:context="example.javatpoint.com.optionmenu.MainActivity">
5.
6. <item android:id="@+id/item1"
7. android:title="Item 1"
8. app:showAsAction="always"
9. android:icon="@android:drawable/btn_star"/>
10. <item android:id="@+id/item2"
11. android:title="Item 2"
12. app:showAsAction="ifRoom"
13. android:icon="@android:drawable/btn_plus"/>
14. <item android:id="@+id/item3"
15. android:title="Item 3"
16. app:showAsAction="withText"
17. android:icon="@android:drawable/btn_plus"/>
18. </menu>
activity_main.xml
Drag one listview from the pallete, now the xml file will look like this:
File: activity_main.xml
main_menu.xml
Let's write the code to display the context menu on press of the listview.
File: MainActivity.java
1. package example.javatpoint.com.contextmenu;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.ContextMenu;
6. import android.view.MenuInflater;
7. import android.view.MenuItem;
8. import android.view.View;
9. import android.widget.ArrayAdapter;
10. import android.widget.ListView;
11. import android.widget.Toast;
12.
13. public class MainActivity extends AppCompatActivity {
14. ListView listView;
15. String contacts[]={"Ajay","Sachin","Sumit","Tarun","Yogesh"};
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_main);
20. listView=(ListView)findViewById(R.id.listView);
21. ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.
R.layout.simple_list_item_1,contacts);
22. listView.setAdapter(adapter);
23. // Register the ListView for Context menu
24. registerForContextMenu(listView);
25. }
26. @Override
27. public void onCreateContextMenu(ContextMenu menu, View v, ContextMe
nu.ContextMenuInfo menuInfo)
28. {
29. super.onCreateContextMenu(menu, v, menuInfo);
30. MenuInflater inflater = getMenuInflater();
31. inflater.inflate(R.menu.menu_main, menu);
32. menu.setHeaderTitle("Select The Action");
33. }
34. @Override
35. public boolean onContextItemSelected(MenuItem item){
36. if(item.getItemId()==R.id.call){
37. Toast.makeText(getApplicationContext(),"calling code",Toast.LENGTH_L
ONG).show();
38. }
39. else if(item.getItemId()==R.id.sms){
40. Toast.makeText(getApplicationContext(),"sending sms code",Toast.LENGTH_LO
NG).show();
41. }else{
42. return false;
43. }
44. return true;
45. }
46. }
Output:
activity_main.xml
File: activity_main.xml
It contains three items as show below. It is created inside the res/menu directory.
File: poupup_menu.xml
File: MainActivity.java
1. package example.javatpoint.com.popupmenu;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.view.MenuItem;
6. import android.view.View;
7. import android.widget.Button;
8. import android.widget.PopupMenu;
9. import android.widget.Toast;
10.
11. public class MainActivity extends AppCompatActivity {
12. Button button;
13.
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. button = (Button) findViewById(R.id.button);
20. button.setOnClickListener(new View.OnClickListener() {
21.
22. @Override
23. public void onClick(View v) {
24. //Creating the instance of PopupMenu
25. PopupMenu popup = new PopupMenu(MainActivity.this, button);
26. //Inflating the Popup using xml file
27. popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMe
nu());
28.
29. //registering popup with OnMenuItemClickListener
30. popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickList
ener() {
31. public boolean onMenuItemClick(MenuItem item) {
32. Toast.makeText(MainActivity.this,"You Clicked : " + item.getTitle(), Toast
.LENGTH_SHORT).show();
33. return true;
34. }
35. });
36.
37. popup.show();//showing popup menu
38. }
39. });//closing the setOnClickListener method
40. }
41. }
1. Started
2. Bound
1) Started Service
A service is started when component (like activity) calls startService() method, now it
runs in the background indefinitely. It is stopped by stopService() method. The
service can stop itself by calling the stopSelf() method.
2) Bound Service
A service is bound when another component (e.g. client) calls bindService() method.
The client can unbind the service by calling the unbindService() method.
The service cannot be stopped until all clients unbind the service.
Understanding Started and Bound Service by background
music example
Suppose, I want to play music in the background, so call startService() method. But I
want to get information of the current song being played, I will bind the service that
provides information about the current song.
Drag the 3 buttons from the pallete, now the activity_main.xml will look like this:
File: activity_main.xml
activity_next.xml
File: activity_next.xml
Service class
Now create the service implemenation class by inheriting the Service class and
overridding its callback methods.
File: MyService.java
1. package example.javatpoint.com.androidservice;
2.
3. import android.app.Service;
4. import android.content.Intent;
5. import android.media.MediaPlayer;
6. import android.os.IBinder;
7. import android.support.annotation.Nullable;
8. import android.widget.Toast;
9.
10. public class MyService extends Service {
11. MediaPlayer myPlayer;
12. @Nullable
13. @Override
14. public IBinder onBind(Intent intent) {
15. return null;
16. }
17. @Override
18. public void onCreate() {
19. Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
20.
21. myPlayer = MediaPlayer.create(this, R.raw.sun);
22. myPlayer.setLooping(false); // Set looping
23. }
24. @Override
25. public void onStart(Intent intent, int startid) {
26. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
27. myPlayer.start();
28. }
29. @Override
30. public void onDestroy() {
31. Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
32. myPlayer.stop();
33. }
34. }
Activity class
Now create the MainActivity class to perform event handling. Here, we are writing
the code to start and stop service. Additionally, calling the second activity on
buttonNext.
File: MainActivity.java
1. package example.javatpoint.com.androidservice;
2.
3. import android.content.Intent;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.widget.Button;
8.
9. public class MainActivity extends AppCompatActivity implements View.OnCl
ickListener{
10. Button buttonStart, buttonStop,buttonNext;
11. @Override
12. protected void onCreate(Bundle savedInstanceState) {
13. super.onCreate(savedInstanceState);
14. setContentView(R.layout.activity_main);
15.
16. buttonStart = findViewById(R.id.buttonStart);
17. buttonStop = findViewById(R.id.buttonStop);
18. buttonNext = findViewById(R.id.buttonNext);
19.
20. buttonStart.setOnClickListener(this);
21. buttonStop.setOnClickListener(this);
22. buttonNext.setOnClickListener(this);
23.
24.
25. }
26. public void onClick(View src) {
27. switch (src.getId()) {
28. case R.id.buttonStart:
29.
30. startService(new Intent(this, MyService.class));
31. break;
32. case R.id.buttonStop:
33. stopService(new Intent(this, MyService.class));
34. break;
35. case R.id.buttonNext:
36. Intent intent=new Intent(this,NextPage.class);
37. startActivity(intent);
38. break;
39. }
40. }
41. }
NextPage class
File: NextPage.java
1. package example.javatpoint.com.androidservice;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class NextPage extends AppCompatActivity {
7.
8. @Override
9. protected void onCreate(Bundle savedInstanceState) {
10. super.onCreate(savedInstanceState);
11. setContentView(R.layout.activity_next);
12. }
13. }
File: AndroidManifest.xml
The Android AlarmManager holds a CPU wake lock that provides guarantee not to
sleep the phone until broadcast is handled.
File: activity_main.xml
Activity class
The activity class starts the alarm service when user clicks on the button.
File: MainActivity.java
1. package example.javatpoint.com.alarmmanager;
2.
3. import android.app.AlarmManager;
4. import android.app.PendingIntent;
5. import android.content.Intent;
6. import android.support.v7.app.AppCompatActivity;
7. import android.os.Bundle;
8. import android.view.View;
9. import android.widget.Button;
10. import android.widget.EditText;
11. import android.widget.Toast;
12.
13. public class MainActivity extends AppCompatActivity {
14. Button start;
15. @Override
16. protected void onCreate(Bundle savedInstanceState) {
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19. start= findViewById(R.id.button);
20.
21. start.setOnClickListener(new View.OnClickListener() {
22. @Override
23. public void onClick(View view) {
24. startAlert();
25. }
26. });
27. }
28.
29. public void startAlert(){
30. EditText text = findViewById(R.id.time);
31. int i = Integer.parseInt(text.getText().toString());
32. Intent intent = new Intent(this, MyBroadcastReceiver.class);
33. PendingIntent pendingIntent = PendingIntent.getBroadcast(
34. this.getApplicationContext(), 234324243, intent, 0);
35. AlarmManager alarmManager = (AlarmManager) getSystemService(ALAR
M_SERVICE);
36. alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
37. + (i * 1000), pendingIntent);
38. Toast.makeText(this, "Alarm set in " + i + " seconds",Toast.LENGTH_LONG).show()
;
39. }
40. }
File: MyBroadcastReceiver.java
1. package example.javatpoint.com.alarmmanager;
2.
3. import android.content.BroadcastReceiver;
4. import android.content.Context;
5. import android.content.Intent;
6. import android.media.MediaPlayer;
7. import android.widget.Toast;
8.
9. public class MyBroadcastReceiver extends BroadcastReceiver {
10. MediaPlayer mp;
11. @Override
12. public void onReceive(Context context, Intent intent) {
13. mp=MediaPlayer.create(context, R.raw.alarm);
14. mp.start();
15. Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
16. }
17. }
File: AndroidManifest.xml
Here, we are going to see a simple example to play the audio file. In the next page,
we will see the example to control the audio playback like start, stop, pause etc.
MediaPlayer class
The android.media.MediaPlayer class is used to control the audio or video files.
There are many methods of MediaPlayer class. Some of them are as follows:
Method Description
public void setDataSource(String path) sets the data source (file path or http
url) to use.
public void setLooping(boolean looping) sets the player for looping or non-
looping.
Let's write the code of to play the audio file. Here, we are going to play maine.mp3
file located inside the sdcard/Music directory.
File: MainActivity.java
1. package com.example.audiomediaplayer1;
2.
3. import android.media.MediaPlayer;
4. import android.net.Uri;
5. import android.os.Bundle;
6. import android.app.Activity;
7. import android.view.Menu;
8. import android.widget.MediaController;
9. import android.widget.VideoView;
10.
11. public class MainActivity extends Activity {
12.
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17.
18. MediaPlayer mp=new MediaPlayer();
19. try{
20. mp.setDataSource("/sdcard/Music/maine.mp3");//Write your location here
21. mp.prepare();
22. mp.start();
23.
24. }catch(Exception e){e.printStackTrace();}
25.
26. }
27.
28. @Override
29. public boolean onCreateOptionsMenu(Menu menu) {
30. // Inflate the menu; this adds items to the action bar if it is present.
31. getMenuInflater().inflate(R.menu.activity_main, menu);
32. return true;
33. }
34.
35. }
activity_main.xml
Drag three buttons from pallete to start, stop and pause the audio play. Now the xml
file will look like this:
File: MainActivity.java
1. <RelativeLayout xmlns:androclass="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. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:id="@+id/textView1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentTop="true"
16. android:layout_marginTop="30dp"
17. android:text="Audio Controller" />
18.
19. <Button
20. android:id="@+id/button1"
21. style="?android:attr/buttonStyleSmall"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_alignLeft="@+id/textView1"
25. android:layout_below="@+id/textView1"
26. android:layout_marginTop="48dp"
27. android:text="start" />
28.
29. <Button
30. android:id="@+id/button2"
31. style="?android:attr/buttonStyleSmall"
32. android:layout_width="wrap_content"
33. android:layout_height="wrap_content"
34. android:layout_alignTop="@+id/button1"
35. android:layout_toRightOf="@+id/button1"
36. android:text="pause" />
37.
38. <Button
39. android:id="@+id/button3"
40. style="?android:attr/buttonStyleSmall"
41. android:layout_width="wrap_content"
42. android:layout_height="wrap_content"
43. android:layout_alignTop="@+id/button2"
44. android:layout_toRightOf="@+id/button2"
45. android:text="stop" />
46.
47. </RelativeLayout>
Activity class
Let's write the code to start, pause and stop the audio player.
File: MainActivity.java
1. package com.example.audioplay;
2.
3. import android.media.MediaPlayer;
4. import android.os.Bundle;
5. import android.os.Environment;
6. import android.app.Activity;
7. import android.view.Menu;
8. import android.view.View;
9. import android.view.View.OnClickListener;
10. import android.widget.Button;
11.
12. public class MainActivity extends Activity {
13. Button start,pause,stop;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. start=(Button)findViewById(R.id.button1);
20. pause=(Button)findViewById(R.id.button2);
21. stop=(Button)findViewById(R.id.button3);
22. //creating media player
23. final MediaPlayer mp=new MediaPlayer();
24. try{
25. //you can change the path, here path is external directory(e.g. sdcar
d) /Music/maine.mp3
26. mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/
Music/maine.mp3");
27.
28. mp.prepare();
29. }catch(Exception e){e.printStackTrace();}
30.
31. start.setOnClickListener(new OnClickListener() {
32. @Override
33. public void onClick(View v) {
34. mp.start();
35. }
36. });
37. pause.setOnClickListener(new OnClickListener() {
38. @Override
39. public void onClick(View v) {
40. mp.pause();
41. }
42. });
43. stop.setOnClickListener(new OnClickListener() {
44. @Override
45. public void onClick(View v) {
46. mp.stop();
47. }
48. });
49. }
50. }
Output:
VideoView class
Method Description
public void setVideoURI (Uri uri) sets the URI of the video file.
activity_main.xml
Drag the VideoView from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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. <VideoView
8. android:id="@+id/videoView1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_centerVertical="true" />
13.
14. </RelativeLayout>
Activity class
Let's write the code of to play the video file. Here, we are going to play 1.mp4 file
located inside the sdcard/media directory.
File: MainActivity.java
1. package com.example.video1;
2.
3. import android.net.Uri;
4. import android.os.Bundle;
5. import android.app.Activity;
6. import android.view.Menu;
7. import android.widget.MediaController;
8. import android.widget.VideoView;
9.
10. public class MainActivity extends Activity {
11.
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16.
17. VideoView videoView =(VideoView)findViewById(R.id.videoView1);
18.
19. //Creating MediaController
20. MediaController mediaController= new MediaController(this);
21. mediaController.setAnchorView(videoView);
22.
23. //specify the location of media file
24. Uri uri=Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/
media/1.mp4");
25.
26. //Setting MediaController and URI, then starting the videoView
27. videoView.setMediaController(mediaController);
28. videoView.setVideoURI(uri);
29. videoView.requestFocus();
30. videoView.start();
31.
32. }
33.
34. @Override
35. public boolean onCreateOptionsMenu(Menu menu) {
36. // Inflate the menu; this adds items to the action bar if it is present.
37. getMenuInflater().inflate(R.menu.activity_main, menu);
38. return true;
39. }
40.
41. }
After recording the media, we can create a sound file that can be played later.
In this example, we are going to record the audio file and storing it in the external
directory in 3gp format.
activity_main.xml
Drag 2 buttons from the pallete, one to start the recording and another stop the
recording. Here, we are registering the view with the listener in xml file
using android:onClick.
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <Button
12. android:id="@+id/button1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentLeft="true"
16. android:layout_alignParentTop="true"
17. android:layout_marginLeft="68dp"
18. android:layout_marginTop="50dp"
19. android:text="Start Recording"
20. android:onClick="startRecording"
21. />
22.
23. <Button
24. android:id="@+id/button2"
25. android:layout_width="wrap_content"
26. android:layout_height="wrap_content"
27. android:layout_alignLeft="@+id/button1"
28. android:layout_below="@+id/button1"
29. android:layout_marginTop="64dp"
30. android:text="Stop Recording"
31. android:onClick="stopRecording"
32. />
33.
34. </RelativeLayout>
Activity class
File: MainActivity.java
1. package com.javatpoint.mediarecorder;
2. import java.io.File;
3. import java.io.IOException;
4. import android.app.Activity;
5. import android.content.ContentResolver;
6. import android.content.ContentValues;
7. import android.content.Intent;
8. import android.media.MediaRecorder;
9. import android.net.Uri;
10. import android.os.Bundle;
11. import android.os.Environment;
12. import android.provider.MediaStore;
13. import android.util.Log;
14. import android.view.View;
15. import android.widget.Button;
16. import android.widget.Toast;
17.
18. public class MainActivity extends Activity {
19. MediaRecorder recorder;
20. File audiofile = null;
21. static final String TAG = "MediaRecording";
22. Button startButton,stopButton;
23.
24. @Override
25. public void onCreate(Bundle savedInstanceState) {
26. super.onCreate(savedInstanceState);
27. setContentView(R.layout.activity_main);
28. startButton = (Button) findViewById(R.id.button1);
29. stopButton = (Button) findViewById(R.id.button2);
30. }
31.
32. public void startRecording(View view) throws IOException {
33. startButton.setEnabled(false);
34. stopButton.setEnabled(true);
35. //Creating file
36. File dir = Environment.getExternalStorageDirectory();
37. try {
38. audiofile = File.createTempFile("sound", ".3gp", dir);
39. } catch (IOException e) {
40. Log.e(TAG, "external storage access error");
41. return;
42. }
43. //Creating MediaRecorder and specifying audio source, output format,
encoder & output format
44. recorder = new MediaRecorder();
45. recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
46. recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
47. recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
48. recorder.setOutputFile(audiofile.getAbsolutePath());
49. recorder.prepare();
50. recorder.start();
51. }
52.
53. public void stopRecording(View view) {
54. startButton.setEnabled(true);
55. stopButton.setEnabled(false);
56. //stopping recorder
57. recorder.stop();
58. recorder.release();
59. //after stopping the recorder, create the sound file and add it to media
library.
60. addRecordingToMediaLibrary();
61. }
62.
63. protected void addRecordingToMediaLibrary() {
64. //creating content values of size 4
65. ContentValues values = new ContentValues(4);
66. long current = System.currentTimeMillis();
67. values.put(MediaStore.Audio.Media.TITLE, "audio" + audiofile.getName())
;
68. values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
69. values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
70. values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());
71.
72. //creating content resolver and storing it in the external content uri
73. ContentResolver contentResolver = getContentResolver();
74. Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
75. Uri newUri = contentResolver.insert(base, values);
76.
77. //sending broadcast message to scan the media file so that it can be av
ailable
78. sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri)
);
79. Toast.makeText(this, "Added File " + newUri, Toast.LENGTH_LONG).show(
);
80. }
81. }
Method Description
int speak (String text, int converts the text into speech. Queue Mode may be
queueMode, QUEUE_ADD or QUEUE_FLUSH. Request parameters can
HashMap params) be null, KEY_PARAM_STREAM, KEY_PARAM_VALUME etc.
TextToSpeech.OnInitListener Interface
You need to implement TextToSpeech.OnInitListener interface, for performing event
handling on TextToSpeech engine.
Method Description
void onInit (int Called to signal the completion of the TextToSpeech engine
status) initialization. The status can be SUCCESS or ERROR.
activity_main.xml
Drag one textview, one edittext and one button for the layout. Now the
activity_main.xml file will look like this:
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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. <EditText
8. android:id="@+id/editText1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="77dp"
14. android:layout_marginTop="42dp"
15. android:ems="10" >
16.
17. <requestFocus />
18. </EditText>
19.
20. <Button
21. android:id="@+id/button1"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_alignLeft="@+id/editText1"
25. android:layout_below="@+id/editText1"
26. android:layout_marginLeft="59dp"
27. android:layout_marginTop="39dp"
28. android:text="Speak" />
29.
30. <TextView
31. android:id="@+id/textView1"
32. android:layout_width="wrap_content"
33. android:layout_height="wrap_content"
34. android:layout_alignBaseline="@+id/editText1"
35. android:layout_alignBottom="@+id/editText1"
36. android:layout_alignParentLeft="true"
37. android:text="Enter Text:" />
38.
39. </RelativeLayout>
Activity class
File: MainActivity.java
1. package com.example.texttospeech;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6. import java.util.Locale;
7.
8. import android.app.Activity;
9. import android.os.Bundle;
10. import android.speech.tts.TextToSpeech;
11. import android.util.Log;
12. import android.view.View;
13. import android.widget.Button;
14. import android.widget.EditText;
15. public class MainActivity extends Activity implements
16. TextToSpeech.OnInitListener {
17. /** Called when the activity is first created. */
18.
19. private TextToSpeech tts;
20. private Button buttonSpeak;
21. private EditText editText;
22.
23. @Override
24. public void onCreate(Bundle savedInstanceState) {
25. super.onCreate(savedInstanceState);
26. setContentView(R.layout.activity_main);
27.
28. tts = new TextToSpeech(this, this);
29. buttonSpeak = (Button) findViewById(R.id.button1);
30. editText = (EditText) findViewById(R.id.editText1);
31.
32. buttonSpeak.setOnClickListener(new View.OnClickListener() {
33. @Override
34. public void onClick(View arg0) {
35. speakOut();
36. }
37.
38. });
39. }
40.
41. @Override
42. public void onDestroy() {
43. // Don't forget to shutdown tts!
44. if (tts != null) {
45. tts.stop();
46. tts.shutdown();
47. }
48. super.onDestroy();
49. }
50.
51. @Override
52. public void onInit(int status) {
53.
54. if (status == TextToSpeech.SUCCESS) {
55.
56. int result = tts.setLanguage(Locale.US);
57.
58. if (result == TextToSpeech.LANG_MISSING_DATA
59. || result == TextToSpeech.LANG_NOT_SUPPORTED) {
60. Log.e("TTS", "This Language is not supported");
61. } else {
62. buttonSpeak.setEnabled(true);
63. speakOut();
64. }
65.
66. } else {
67. Log.e("TTS", "Initilization Failed!");
68. }
69.
70. }
71.
72. private void speakOut() {
73. String text = editText.getText().toString();
74. tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
75. }
76.
77. @Override
78. public boolean onCreateOptionsMenu(Menu menu) {
79. // Inflate the menu; this adds items to the action bar if it is present.
80. getMenuInflater().inflate(R.menu.activity_main, menu);
81. return true;
82. }
83.
84. }
You need to run it on the Real Device (e.g. Mobile) to test the application.
In this example, we are going to see the android texttospeech example with speed
and pitch option.
activity_main.xml
Drag 2 textviews, 1 edittext, 1 spinner and 1 button for the layout. Now the
activity_main.xml file will look like this:
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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. <EditText
8. android:id="@+id/editText1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignBaseline="@+id/textView1"
12. android:layout_alignBottom="@+id/textView1"
13. android:layout_alignParentRight="true"
14. android:layout_marginRight="58dp"
15. android:ems="10" >
16.
17. <requestFocus />
18. </EditText>
19.
20. <Button
21. android:id="@+id/button1"
22. android:layout_width="wrap_content"
23. android:layout_height="wrap_content"
24. android:layout_below="@+id/editText1"
25. android:layout_centerHorizontal="true"
26. android:layout_marginTop="28dp"
27. android:text="Speak" />
28.
29. <TextView
30. android:id="@+id/textView2"
31. android:layout_width="wrap_content"
32. android:layout_height="wrap_content"
33. android:layout_below="@+id/button1"
34. android:layout_marginTop="62dp"
35. android:layout_toLeftOf="@+id/editText1"
36. android:text="Speed:" />
37.
38. <TextView
39. android:id="@+id/textView1"
40. android:layout_width="wrap_content"
41. android:layout_height="wrap_content"
42. android:layout_alignLeft="@+id/textView2"
43. android:layout_alignParentTop="true"
44. android:layout_marginTop="42dp"
45. android:text="Text:" />
46.
47. <Spinner
48. android:id="@+id/spinner1"
49. android:layout_width="200dp"
50. android:layout_height="wrap_content"
51. android:layout_below="@+id/button1"
52. android:layout_centerHorizontal="true"
53. android:layout_marginTop="43dp" />
54.
55. </RelativeLayout>
Activity class
File: MainActivity.java
1. package com.example.texttospeechspeed;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6.
7. import java.util.ArrayList;
8. import java.util.List;
9. import java.util.Locale;
10. import android.speech.tts.TextToSpeech;
11. import android.util.Log;
12. import android.view.View;
13. import android.widget.AdapterView;
14. import android.widget.AdapterView.OnItemSelectedListener;
15. import android.widget.ArrayAdapter;
16. import android.widget.Button;
17. import android.widget.EditText;
18. import android.widget.Spinner;
19. import android.widget.Toast;
20. public class MainActivity extends Activity implements
21. TextToSpeech.OnInitListener,OnItemSelectedListener {
22. /** Called when the activity is first created. */
23.
24. private TextToSpeech tts;
25. private Button buttonSpeak;
26. private EditText editText;
27. private Spinner speedSpinner,pitchSpinner;
28.
29. private static String speed="Normal";
30. @Override
31. public void onCreate(Bundle savedInstanceState) {
32. super.onCreate(savedInstanceState);
33. setContentView(R.layout.activity_main);
34.
35. tts = new TextToSpeech(this, this);
36. buttonSpeak = (Button) findViewById(R.id.button1);
37. editText = (EditText) findViewById(R.id.editText1);
38. speedSpinner = (Spinner) findViewById(R.id.spinner1);
39.
40. //load data in spinner
41. loadSpinnerData();
42. speedSpinner.setOnItemSelectedListener(this);
43.
44. //button click event
45. buttonSpeak.setOnClickListener(new View.OnClickListener() {
46. @Override
47. public void onClick(View arg0) {
48. setSpeed();
49. speakOut();
50. }
51.
52. });
53. }
54.
55.
56. @Override
57. public void onInit(int status) {
58.
59. if (status == TextToSpeech.SUCCESS) {
60.
61. int result = tts.setLanguage(Locale.US);
62.
63. if (result == TextToSpeech.LANG_MISSING_DATA
64. || result == TextToSpeech.LANG_NOT_SUPPORTED) {
65. Log.e("TTS", "This Language is not supported");
66. } else {
67. buttonSpeak.setEnabled(true);
68. speakOut();
69. }
70.
71. } else { Log.e("TTS", "Initilization Failed!");}
72.
73. }
74.
75. @Override
76. public void onDestroy() {
77. // Don't forget to shutdown tts!
78. if (tts != null) {
79. tts.stop();
80. tts.shutdown();
81. }
82. super.onDestroy();
83. }
84.
85. private void setSpeed(){
86. if(speed.equals("Very Slow")){
87. tts.setSpeechRate(0.1f);
88. }
89. if(speed.equals("Slow")){
90. tts.setSpeechRate(0.5f);
91. }
92. if(speed.equals("Normal")){
93. tts.setSpeechRate(1.0f);//default 1.0
94. }
95. if(speed.equals("Fast")){
96. tts.setSpeechRate(1.5f);
97. }
98. if(speed.equals("Very Fast")){
99. tts.setSpeechRate(2.0f);
100. }
101. //for setting pitch you may call
102. //tts.setPitch(1.0f);//default 1.0
103. }
104.
105. private void speakOut() {
106. String text = editText.getText().toString();
107. tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
108. }
109.
110. private void loadSpinnerData() {
111. //Data for speed Spinner
112. List<String> lables = new ArrayList<String>();
113. lables.add("Very Slow");
114. lables.add("Slow");
115. lables.add("Normal");
116. lables.add("Fast");
117. lables.add("Very Fast");
118.
119. // Creating adapter for spinner
120. ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,andr
oid.R.layout.simple_spinner_item, lables);
121.
122. // Drop down layout style - list view with radio button
123. dataAdapter.setDropDownViewResource(android.R.layout.simple_spi
nner_dropdown_item);
124.
125. // attaching data adapter to spinner
126. speedSpinner.setAdapter(dataAdapter);
127.
128. }
129.
130. @Override
131. public void onItemSelected(AdapterView<?> parent, View view, int po
sition,
132. long id) {
133. // On selecting a spinner item
134. speed = parent.getItemAtPosition(position).toString();
135.
136. Toast.makeText(parent.getContext(), "You selected: " + speed,
137. Toast.LENGTH_LONG).show();
138. }
139.
140. @Override
141. public void onNothingSelected(AdapterView<?> arg0) {
142.
143. }
144.
145.
146. @Override
147. public boolean onCreateOptionsMenu(Menu menu) {
148. // Inflate the menu; this adds items to the action bar if it is present.
149. getMenuInflater().inflate(R.menu.activity_main, menu);
150. return true;
151. }
152.
153. }
Android TelephonyManager Tutorial
The android.telephony.TelephonyManager class provides information about the
telephony services such as subscriber id, sim serial number, phone network type etc.
Moreover, you can determine the phone state etc.
activity_main.xml
Drag one textview from the pallete, now the xml file will look like this.
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:id="@+id/textView1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentLeft="true"
16. android:layout_alignParentTop="true"
17. android:layout_marginLeft="38dp"
18. android:layout_marginTop="30dp"
19. android:text="Phone Details:" />
20.
21. </RelativeLayout>
Activity class
Now, write the code to display the information about the telephony services.
File: MainActivity.java
1. package com.javatpoint.telephonymanager;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.content.Context;
6. import android.telephony.TelephonyManager;
7. import android.view.Menu;
8. import android.widget.TextView;
9.
10. public class MainActivity extends Activity {
11. TextView textView1;
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16.
17. textView1=(TextView)findViewById(R.id.textView1);
18.
19. //Get the instance of TelephonyManager
20. TelephonyManager tm=(TelephonyManager)getSystemService(Context.TELEPH
ONY_SERVICE);
21.
22. //Calling the methods of TelephonyManager the returns the information
23. String IMEINumber=tm.getDeviceId();
24. String subscriberID=tm.getDeviceId();
25. String SIMSerialNumber=tm.getSimSerialNumber();
26. String networkCountryISO=tm.getNetworkCountryIso();
27. String SIMCountryISO=tm.getSimCountryIso();
28. String softwareVersion=tm.getDeviceSoftwareVersion();
29. String voiceMailNumber=tm.getVoiceMailNumber();
30.
31. //Get the phone type
32. String strphoneType="";
33.
34. int phoneType=tm.getPhoneType();
35.
36. switch (phoneType)
37. {
38. case (TelephonyManager.PHONE_TYPE_CDMA):
39. strphoneType="CDMA";
40. break;
41. case (TelephonyManager.PHONE_TYPE_GSM):
42. strphoneType="GSM";
43. break;
44. case (TelephonyManager.PHONE_TYPE_NONE):
45. strphoneType="NONE";
46. break;
47. }
48.
49. //getting information if phone is in roaming
50. boolean isRoaming=tm.isNetworkRoaming();
51.
52. String info="Phone Details:\n";
53. info+="\n IMEI Number:"+IMEINumber;
54. info+="\n SubscriberID:"+subscriberID;
55. info+="\n Sim Serial Number:"+SIMSerialNumber;
56. info+="\n Network Country ISO:"+networkCountryISO;
57. info+="\n SIM Country ISO:"+SIMCountryISO;
58. info+="\n Software Version:"+softwareVersion;
59. info+="\n Voice Mail Number:"+voiceMailNumber;
60. info+="\n Phone Network Type:"+strphoneType;
61. info+="\n In Roaming? :"+isRoaming;
62.
63. textView1.setText(info);//displaying the information in the textView
64. }
65.
66.
67. }
AndroidManifest.xml
File: AndroidManifest.xml
Output:
Drag the EditText and Button from the pallete, now the activity_main.xml file will like
this:
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentTop="true"
12. android:layout_centerHorizontal="true"
13. android:layout_marginTop="118dp"
14. android:text="Call" />
15.
16. <EditText
17. android:id="@+id/editText1"
18. android:layout_width="wrap_content"
19. android:layout_height="wrap_content"
20. android:layout_alignParentTop="true"
21. android:layout_centerHorizontal="true"
22. android:layout_marginTop="25dp"
23. android:ems="10" />
24.
25. </RelativeLayout>
Activity class
Let's write the code to make the phone call via intent.
File: MainActivity.java
1. package com.example.phonecall;
2.
3. import android.net.Uri;
4. import android.os.Bundle;
5. import android.app.Activity;
6. import android.content.Intent;
7. import android.view.Menu;
8. import android.view.View;
9. import android.view.View.OnClickListener;
10. import android.widget.Button;
11. import android.widget.EditText;
12.
13. public class MainActivity extends Activity {
14. EditText edittext1;
15. Button button1;
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_main);
20.
21. //Getting the edittext and button instance
22. edittext1=(EditText)findViewById(R.id.editText1);
23. button1=(Button)findViewById(R.id.button1);
24.
25. //Performing action on button click
26. button1.setOnClickListener(new OnClickListener(){
27.
28. @Override
29. public void onClick(View arg0) {
30. String number=edittext1.getText().toString();
31. Intent callIntent = new Intent(Intent.ACTION_CALL);
32. callIntent.setData(Uri.parse("tel:"+number));
33. startActivity(callIntent);
34. }
35.
36. });
37. }
38.
39. @Override
40. public boolean onCreateOptionsMenu(Menu menu) {
41. // Inflate the menu; this adds items to the action bar if it is present.
42. getMenuInflater().inflate(R.menu.activity_main, menu);
43. return true;
44. }
45.
46. }
Install and Run the apk file on the Real Device (e.g. Mobile) to make the phone
call.
Output:
How to send sms in android
We can send sms in android via intent. You need to write only 4 lines of code the
send sms in android.
Drag the 2 edittexts, 2 textviews and 1 button from the pallete, now the
activity_main.xml file will like this:
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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. <EditText
8. android:id="@+id/editText1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentRight="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginRight="20dp"
14. android:ems="10" />
15.
16. <EditText
17. android:id="@+id/editText2"
18. android:layout_width="wrap_content"
19. android:layout_height="wrap_content"
20. android:layout_alignLeft="@+id/editText1"
21. android:layout_below="@+id/editText1"
22. android:layout_marginTop="26dp"
23. android:ems="10"
24. android:inputType="textMultiLine" />
25.
26. <TextView
27. android:id="@+id/textView1"
28. android:layout_width="wrap_content"
29. android:layout_height="wrap_content"
30. android:layout_alignBaseline="@+id/editText1"
31. android:layout_alignBottom="@+id/editText1"
32. android:layout_toLeftOf="@+id/editText1"
33. android:text="Mobile No:" />
34.
35. <TextView
36. android:id="@+id/textView2"
37. android:layout_width="wrap_content"
38. android:layout_height="wrap_content"
39. android:layout_alignBaseline="@+id/editText2"
40. android:layout_alignBottom="@+id/editText2"
41. android:layout_alignLeft="@+id/textView1"
42. android:text="Message:" />
43.
44. <Button
45. android:id="@+id/button1"
46. android:layout_width="wrap_content"
47. android:layout_height="wrap_content"
48. android:layout_alignLeft="@+id/editText2"
49. android:layout_below="@+id/editText2"
50. android:layout_marginLeft="34dp"
51. android:layout_marginTop="48dp"
52. android:text="Send SMS" />
53.
54. </RelativeLayout>
1. <uses-permission android:name="android.permission.SEND_SMS"/>
2.
File: Android-Manifest.xml
Activity class
Let's write the code to make the phone call via intent.
File: MainActivity.java
1. package com.example.sendsms;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.app.PendingIntent;
6. import android.content.Intent;
7. import android.telephony.SmsManager;
8. import android.view.Menu;
9. import android.view.View;
10. import android.view.View.OnClickListener;
11. import android.widget.Button;
12. import android.widget.EditText;
13. import android.widget.Toast;
14.
15. public class MainActivity extends Activity {
16.
17. EditText mobileno,message;
18. Button sendsms;
19. @Override
20. protected void onCreate(Bundle savedInstanceState) {
21. super.onCreate(savedInstanceState);
22. setContentView(R.layout.activity_main);
23.
24. mobileno=(EditText)findViewById(R.id.editText1);
25. message=(EditText)findViewById(R.id.editText2);
26. sendsms=(Button)findViewById(R.id.button1);
27.
28. //Performing action on button click
29. sendsms.setOnClickListener(new OnClickListener() {
30.
31. @Override
32. public void onClick(View arg0) {
33. String no=mobileno.getText().toString();
34. String msg=message.getText().toString();
35.
36. //Getting intent and PendingIntent instance
37. Intent intent=new Intent(getApplicationContext(),MainActivity.class)
;
38. PendingIntent pi=PendingIntent.getActivity(getApplicationContext(), 0, inte
nt,0);
39.
40. //Get the SmsManager instance and call the sendTextMessage method to s
end message
41. SmsManager sms=SmsManager.getDefault();
42. sms.sendTextMessage(no, null, msg, pi,null);
43.
44. Toast.makeText(getApplicationContext(), "Message Sent successfully!",
45. Toast.LENGTH_LONG).show();
46. }
47. });
48. }
49.
50. @Override
51. public boolean onCreateOptionsMenu(Menu menu) {
52. // Inflate the menu; this adds items to the action bar if it is present.
53. getMenuInflater().inflate(R.menu.activity_main, menu);
54. return true;
55. }
56.
57. }
download this example
Install and Run the apk file on the Real Device (e.g. Mobile) to send the sms.
Output:
Android Bluetooth Tutorial
Bluetooth is a way to exchange data with other devices wirelessly. Android provides
Bluetooth API to perform several tasks such as:
o BluetoothAdapter
o BluetoothDevice
o BluetoothSocket
o BluetoothServerSocket
o BluetoothClass
o BluetoothProfile
o BluetoothProfile.ServiceListener
o BluetoothHeadset
o BluetoothA2dp
o BluetoothHealth
o BluetoothHealthCallback
o BluetoothHealthAppConfiguration
android-preferences-example
BluetoothAdapter class
By the help of BluetoothAdapter class, we can perform fundamental tasks such as
initiate device discovery, query a list of paired (bonded) devices, create a
BluetoothServerSocket instance to listen for connection requests etc.
o String ACTION_REQUEST_ENABLE
o String ACTION_REQUEST_DISCOVERABLE
o String ACTION_DISCOVERY_STARTED
o String ACTION_DISCOVERY_FINISHED
activity_main.xml
Drag one textview and three buttons from the pallete, now the activity_main.xml file
will like this:
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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 android:text=""
8. android:id="@+id/out"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content">
11. </TextView>
12. <Button
13. android:id="@+id/button1"
14. android:layout_width="wrap_content"
15. android:layout_height="wrap_content"
16. android:layout_alignParentLeft="true"
17. android:layout_alignParentTop="true"
18. android:layout_marginLeft="30dp"
19. android:layout_marginTop="49dp"
20. android:text="TURN_ON" />
21.
22. <Button
23. android:id="@+id/button2"
24. android:layout_width="wrap_content"
25. android:layout_height="wrap_content"
26. android:layout_alignLeft="@+id/button1"
27. android:layout_below="@+id/button1"
28. android:layout_marginTop="27dp"
29. android:text="DISCOVERABLE" />
30.
31. <Button
32. android:id="@+id/button3"
33. android:layout_width="wrap_content"
34. android:layout_height="wrap_content"
35. android:layout_alignLeft="@+id/button2"
36. android:layout_below="@+id/button2"
37. android:layout_marginTop="28dp"
38. android:text="TURN_OFF" />
39.
40. </RelativeLayout>
Provide Permission
File: AndroidManifest.xml
Activity class
Let's write the code to enable, disable and make bluetooth discoverable.
File: MainActivity.java
1. package com.example.bluetooth;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.view.Menu;
5. import android.app.Activity;
6. import android.bluetooth.BluetoothAdapter;
7. import android.content.Context;
8. import android.content.Intent;
9. import android.os.Bundle;
10. import android.util.Log;
11. import android.view.View;
12. import android.widget.Button;
13. import android.widget.TextView;
14. import android.widget.Toast;
15.
16. public class MainActivity extends Activity {
17. private static final int REQUEST_ENABLE_BT = 0;
18. private static final int REQUEST_DISCOVERABLE_BT = 0;
19. @Override
20. protected void onCreate(Bundle savedInstanceState) {
21. super.onCreate(savedInstanceState);
22. setContentView(R.layout.activity_main);
23. final TextView out=(TextView)findViewById(R.id.out);
24. final Button button1 = (Button) findViewById(R.id.button1);
25. final Button button2 = (Button) findViewById(R.id.button2);
26. final Button button3 = (Button) findViewById(R.id.button3);
27. final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefault
Adapter();
28. if (mBluetoothAdapter == null) {
29. out.append("device not supported");
30. }
31. button1.setOnClickListener(new View.OnClickListener() {
32. public void onClick(View v) {
33. if (!mBluetoothAdapter.isEnabled()) {
34. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_EN
ABLE);
35. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
36. }
37. }
38. });
39. button2.setOnClickListener(new View.OnClickListener() {
40. @Override
41. public void onClick(View arg0) {
42. if (!mBluetoothAdapter.isDiscovering()) {
43. //out.append("MAKING YOUR DEVICE DISCOVERABLE");
44. Toast.makeText(getApplicationContext(), "MAKING YOUR DEVICE DISCOV
ERABLE",
45. Toast.LENGTH_LONG);
46.
47. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQ
UEST_DISCOVERABLE);
48. startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);
49.
50. }
51. }
52. });
53. button3.setOnClickListener(new View.OnClickListener() {
54. @Override
55. public void onClick(View arg0) {
56. mBluetoothAdapter.disable();
57. //out.append("TURN_OFF BLUETOOTH");
58. Toast.makeText(getApplicationContext(), "TURNING_OFF BLUETOOTH", Toast.L
ENGTH_LONG);
59.
60. }
61. });
62. }
63.
64. @Override
65. public boolean onCreateOptionsMenu(Menu menu) {
66. // Inflate the menu; this adds items to the action bar if it is present.
67. getMenuInflater().inflate(R.menu.activity_main, menu);
68. return true;
69. }
70.
71. }
In this example, we are checking if the bluetooth is turned off, if yes then turn it on
and list all the paired devices.
activity_main.xml
Drag one textview from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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/textView1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="18dp"
14. android:layout_marginTop="61dp"
15. android:text="Showing Paired Devices:" />
16.
17. </RelativeLayout>
Provide Permission
File: AndroidManifest.xml
Activity class
Let's write the code to provide the list of paired (bounded) bluetooth devices.
File: MainActivity.java
1. package com.example.bluetoothshowpaired;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6. import java.util.Set;
7. import android.bluetooth.BluetoothAdapter;
8. import android.bluetooth.BluetoothDevice;
9. import android.content.Intent;
10. import android.widget.TextView;
11.
12. public class MainActivity extends Activity {
13. TextView textview1;
14. private static final int REQUEST_ENABLE_BT = 1;
15. BluetoothAdapter btAdapter;
16.
17. /** Called when the activity is first created. */
18. @Override
19. public void onCreate(Bundle savedInstanceState) {
20. super.onCreate(savedInstanceState);
21. setContentView(R.layout.activity_main);
22.
23. textview1 = (TextView) findViewById(R.id.textView1);
24.
25. // Getting the Bluetooth adapter
26. btAdapter = BluetoothAdapter.getDefaultAdapter();
27. textview1.append("\nAdapter: " + btAdapter);
28.
29. CheckBluetoothState();
30. }
31.
32. /* It is called when an activity completes.*/
33. @Override
34. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
35. super.onActivityResult(requestCode, resultCode, data);
36. if (requestCode == REQUEST_ENABLE_BT) {
37. CheckBluetoothState();
38. }
39. }
40.
41. @Override
42. protected void onDestroy() {
43. super.onDestroy();
44. }
45.
46. private void CheckBluetoothState() {
47. // Checks for the Bluetooth support and then makes sure it is turned on
48. // If it isn't turned on, request to turn it on
49. // List paired devices
50. if(btAdapter==null) {
51. textview1.append("\nBluetooth NOT supported. Aborting.");
52. return;
53. } else {
54. if (btAdapter.isEnabled()) {
55. textview1.append("\nBluetooth is enabled...");
56.
57. // Listing paired devices
58. textview1.append("\nPaired Devices are:");
59. Set<BluetoothDevice> devices = btAdapter.getBondedDevices();
60. for (BluetoothDevice device : devices) {
61. textview1.append("\n Device: " + device.getName() + ", " + device);
62. }
63. } else {
64. //Prompt user to turn on Bluetooth
65. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUE
ST_ENABLE);
66. startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
67. }
68. }
69. }
70.
71.
72. @Override
73. public boolean onCreateOptionsMenu(Menu menu) {
74. // Inflate the menu; this adds items to the action bar if it is present.
75. getMenuInflater().inflate(R.menu.activity_main, menu);
76. return true;
77. }
78.
79. }
1. <RelativeLayout xmlns:androclass="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. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="76dp"
14. android:layout_marginTop="67dp"
15. android:text="Enable Wifi" />
16.
17. <Button
18. android:id="@+id/button2"
19. android:layout_width="wrap_content"
20. android:layout_height="wrap_content"
21. android:layout_alignLeft="@+id/button1"
22. android:layout_below="@+id/button1"
23. android:layout_marginTop="44dp"
24. android:text="Disable Wifi" />
25.
26. </RelativeLayout>
Activity class
File: MainActivity.java
1. package com.example.wifi;
2.
3. import android.net.wifi.WifiManager;
4. import android.os.Bundle;
5. import android.app.Activity;
6. import android.content.Context;
7. import android.view.Menu;
8. import android.view.View;
9. import android.view.View.OnClickListener;
10. import android.widget.Button;
11.
12. public class MainActivity extends Activity {
13. Button enableButton,disableButton;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. enableButton=(Button)findViewById(R.id.button1);
20. disableButton=(Button)findViewById(R.id.button2);
21.
22. enableButton.setOnClickListener(new OnClickListener(){
23. public void onClick(View v){
24. WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE)
;
25. wifi.setWifiEnabled(true);
26. }
27. });
28. disableButton.setOnClickListener(new OnClickListener(){
29. public void onClick(View v){
30. WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE)
;
31. wifi.setWifiEnabled(false);
32. }
33. });
34. }
35.
36. @Override
37. public boolean onCreateOptionsMenu(Menu menu) {
38. // Inflate the menu; this adds items to the action bar if it is present.
39. getMenuInflater().inflate(R.menu.activity_main, menu);
40. return true;
41. }
42.
43. }
Add Permission in AndroidManifest.xml
1. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /
>
2. <uses-permission android:name="android.permission.INTERNET" />
3. <uses-permission android:nam
e="android.permission.CHANGE_WIFI_STATE"/>
Output:
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
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.
Drag one imageview and one button from the pallete, now the xml file will look like
this:
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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. <Button
8. android:id="@+id/button1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentBottom="true"
12. android:layout_centerHorizontal="true"
13. android:text="Take a Photo" >
14. </Button>
15.
16. <ImageView
17. android:id="@+id/imageView1"
18. android:layout_width="fill_parent"
19. android:layout_height="fill_parent"
20. android:layout_above="@+id/button1"
21. android:layout_alignParentTop="true"
22. android:src="@drawable/ic_launcher" >
23. </ImageView>
24. </RelativeLayout>
Activity class
Let's write the code to capture image using camera and displaying it on the image
view.
File: MainActivity.java
1. package com.example.simplecamera;
2.
3. import android.app.Activity;
4. import android.content.Intent;
5. import android.graphics.Bitmap;
6. import android.os.Bundle;
7. import android.view.Menu;
8. import android.view.View;
9. import android.widget.Button;
10. import android.widget.ImageView;
11.
12. public class MainActivity extends Activity {
13. private static final int CAMERA_REQUEST = 1888;
14. ImageView imageView;
15. public void onCreate(Bundle savedInstanceState) {
16.
17. super.onCreate(savedInstanceState);
18. setContentView(R.layout.activity_main);
19.
20. imageView = (ImageView) this.findViewById(R.id.imageView1);
21. Button photoButton = (Button) this.findViewById(R.id.button1);
22.
23. photoButton.setOnClickListener(new View.OnClickListener() {
24.
25. @Override
26. public void onClick(View v) {
27. Intent cameraIntent = new Intent(android.provider.MediaStore.ACTIO
N_IMAGE_CAPTURE);
28. startActivityForResult(cameraIntent, CAMERA_REQUEST);
29. }
30. });
31. }
32.
33. protected void onActivityResult(int requestCode, int resultCode, Intent da
ta) {
34. if (requestCode == CAMERA_REQUEST) {
35. Bitmap photo = (Bitmap) data.getExtras().get("data");
36. imageView.setImageBitmap(photo);
37. }
38. }
39.
40. @Override
41. public boolean onCreateOptionsMenu(Menu menu) {
42. // Inflate the menu; this adds items to the action bar if it is present.
43. getMenuInflater().inflate(R.menu.activity_main, menu);
44. return true;
45. }
46.
47. }
Output:
1) Motion Sensors
These are used to measure acceleration forces and rotational forces along with three
axes.
2) Position Sensors
3) Environmental Sensors
1) SensorManager class
1. SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
2) Sensor class
3) SensorEvent class
Its instance is created by the system. It provides information about the sensor.
4) SensorEventListener interface
It provides two call back methods to get information when sensor values (x,y and z)
change or sensor accuracy changes.
activity_main.xml
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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/textView1"
9. android:layout_width="wrap_content"
10. android:layout_height="wrap_content"
11. android:layout_alignParentLeft="true"
12. android:layout_alignParentTop="true"
13. android:layout_marginLeft="92dp"
14. android:layout_marginTop="114dp"
15. android:text="TextView" />
16.
17. </RelativeLayout>
Activity class
Let's write the code that prints values of x axis, y axis and z axis.
File: MainActivity.java
1. package com.example.sensorsimple;
2. import android.app.Activity;
3. import android.os.Bundle;
4. import android.widget.TextView;
5. import android.widget.Toast;
6. import android.hardware.SensorManager;
7. import android.hardware.SensorEventListener;
8. import android.hardware.SensorEvent;
9. import android.hardware.Sensor;
10. import java.util.List;
11. public class MainActivity extends Activity {
12. SensorManager sm = null;
13. TextView textView1 = null;
14. List list;
15.
16. SensorEventListener sel = new SensorEventListener(){
17. public void onAccuracyChanged(Sensor sensor, int accuracy) {}
18. public void onSensorChanged(SensorEvent event) {
19. float[] values = event.values;
20. textView1.setText("x: "+values[0]+"\ny: "+values[1]+"\nz: "+values[2]);
21. }
22. };
23.
24. @Override
25. public void onCreate(Bundle savedInstanceState) {
26. super.onCreate(savedInstanceState);
27. setContentView(R.layout.activity_main);
28.
29. /* Get a SensorManager instance */
30. sm = (SensorManager)getSystemService(SENSOR_SERVICE);
31.
32. textView1 = (TextView)findViewById(R.id.textView1);
33.
34. list = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
35. if(list.size()>0){
36. sm.registerListener(sel, (Sensor) list.get(0), SensorManager.SENSOR_DELAY_N
ORMAL);
37. }else{
38. Toast.makeText(getBaseContext(), "Error: No Accelerometer.", Toast.LENGTH_L
ONG).show();
39. }
40. }
41.
42. @Override
43. protected void onStop() {
44. if(list.size()>0){
45. sm.unregisterListener(sel);
46. }
47. super.onStop();
48. }
49. }
Output:
The android.graphics.Paint class is used with canvas to draw objects. It holds the
information of color and style.
In this example, we are going to display 2D graphics in android.
activity_main.xml
File: activity_main.xml
1. <RelativeLayout xmlns:androclass="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. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <TextView
12. android:layout_width="wrap_content"
13. android:layout_height="wrap_content"
14. android:text="@string/hello_world" />
15.
16. </RelativeLayout>
Activity class
File: MainActivity.java
1. package com.example.simplegraphics;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6. import android.content.Context;
7. import android.graphics.Canvas;
8. import android.graphics.Color;
9. import android.graphics.Paint;
10. import android.view.View;
11.
12. public class MainActivity extends Activity {
13.
14. DemoView demoview;
15. /** Called when the activity is first created. */
16. @Override
17. public void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. demoview = new DemoView(this);
20. setContentView(demoview);
21. }
22.
23. private class DemoView extends View{
24. public DemoView(Context context){
25. super(context);
26. }
27.
28. @Override protected void onDraw(Canvas canvas) {
29. super.onDraw(canvas);
30.
31. // custom drawing code here
32. Paint paint = new Paint();
33. paint.setStyle(Paint.Style.FILL);
34.
35. // make the entire canvas white
36. paint.setColor(Color.WHITE);
37. canvas.drawPaint(paint);
38.
39. // draw blue circle with anti aliasing turned off
40. paint.setAntiAlias(false);
41. paint.setColor(Color.BLUE);
42. canvas.drawCircle(20, 20, 15, paint);
43.
44. // draw green circle with anti aliasing turned on
45. paint.setAntiAlias(true);
46. paint.setColor(Color.GREEN);
47. canvas.drawCircle(60, 20, 15, paint);
48.
49. // draw red rectangle with anti aliasing turned off
50. paint.setAntiAlias(false);
51. paint.setColor(Color.RED);
52. canvas.drawRect(100, 5, 200, 30, paint);
53.
54. // draw the rotated text
55. canvas.rotate(-45);
56.
57. paint.setStyle(Paint.Style.FILL);
58. canvas.drawText("Graphics Rotation", 40, 180, paint);
59.
60. //undo the rotate
61. canvas.restore();
62. }
63. }
64. @Override
65. public boolean onCreateOptionsMenu(Menu menu) {
66. // Inflate the menu; this adds items to the action bar if it is present.
67. getMenuInflater().inflate(R.menu.main, menu);
68. return true;
69. }
70. }
Output:
Android Animation Example
Android provides a large number of classes and interface for the animation
development. Most of the classes and interfaces are given
in android.animation package.
Android Animation enables you to change the object property and behavior at run
time. There are various ways to do animation in android.
The AnimationDrawable class provides methods to start and end the animation.
Even, you can use time based animation.
activity_main.xml
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. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <View
12. />
13.
14. </RelativeLayout>
File: logo.xml
MainActivity class
File: MainActivity.java
1. package com.javatpoint.animation;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.graphics.drawable.AnimationDrawable;
6. import android.widget.ImageView;
7.
8. public class MainActivity extends Activity {
9.
10. ImageView anm;
11. public void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. setContentView(R.layout.logo);
14. anm = (ImageView)findViewById(R.id.anm);
15.
16. anm.setBackgroundResource(R.drawable.animation);
17. // the frame-by-frame animation defined as a xml file within the drawabl
e folder
18.
19. /*
20. * NOTE: It's not possible to start the animation during the onCreate.
21. */
22. }
23. public void onWindowFocusChanged (boolean hasFocus) {
24. super.onWindowFocusChanged(hasFocus);
25. AnimationDrawable frameAnimation =
26. (AnimationDrawable) anm.getBackground();
27. if(hasFocus) {
28. frameAnimation.start();
29. } else {
30. frameAnimation.stop();
31. }
32. }
33.
34. }
You need to have many images. Here, we are using 14 images and all the 14 images
are located inside res/drawable-mdpi directory.
File: animation.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. android:paddingBottom="@dimen/activity_vertical_margin"
6. android:paddingLeft="@dimen/activity_horizontal_margin"
7. android:paddingRight="@dimen/activity_horizontal_margin"
8. android:paddingTop="@dimen/activity_vertical_margin"
9. tools:context=".MainActivity" >
10.
11. <EditText
12. android:id="@+id/editText1"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:layout_alignParentTop="true"
16. android:layout_centerHorizontal="true"
17. android:hint="Username"
18. android:ems="10" >
19.
20. <requestFocus />
21. </EditText>
22.
23. <EditText
24. android:id="@+id/editText2"
25. android:layout_width="wrap_content"
26. android:layout_height="wrap_content"
27. android:layout_alignLeft="@+id/editText1"
28. android:layout_below="@+id/editText1"
29. android:layout_marginTop="67dp"
30. android:ems="10"
31. android:hint="Password"
32. android:inputType="textPassword" />
33.
34. <Button
35. android:id="@+id/button2"
36. android:layout_width="wrap_content"
37. android:layout_height="wrap_content"
38. android:layout_alignParentBottom="true"
39. android:layout_marginBottom="24dp"
40. android:layout_toRightOf="@+id/button1"
41. android:text="New User" />
42.
43. <ProgressBar
44. android:id="@+id/progressBar1"
45. style="?android:attr/progressBarStyleLarge"
46. android:layout_width="wrap_content"
47. android:layout_height="wrap_content"
48. android:layout_alignLeft="@+id/button1"
49. android:layout_below="@+id/editText2"
50. android:layout_marginTop="22dp" />
51.
52. <Button
53. android:id="@+id/button1"
54. android:layout_width="wrap_content"
55. android:layout_height="wrap_content"
56. android:layout_alignLeft="@+id/editText2"
57. android:layout_below="@+id/progressBar1"
58. android:layout_marginLeft="22dp"
59. android:text="Login" />
60.
61. </RelativeLayout>
File: activity_register_user.xml
1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/
android"
2. android:layout_width="fill_parent"
3. android:layout_height="fill_parent" >
4.
5. <EditText
6. android:id="@+id/editText1"
7. android:layout_width="wrap_content"
8. android:layout_height="wrap_content"
9. android:layout_alignParentTop="true"
10. android:layout_centerHorizontal="true"
11. android:layout_marginTop="15dp"
12. android:ems="10"
13. android:hint="Enter UserName" />
14.
15. <EditText
16. android:id="@+id/editText2"
17. android:layout_width="wrap_content"
18. android:layout_height="wrap_content"
19. android:layout_alignLeft="@+id/editText1"
20. android:layout_below="@+id/editText1"
21. android:layout_marginTop="50dp"
22. android:ems="10"
23. android:hint="Enter Password"
24. android:inputType="textPassword" />
25.
26. <Button
27. android:id="@+id/button1"
28. android:layout_width="wrap_content"
29. android:layout_height="wrap_content"
30. android:layout_alignParentBottom="true"
31. android:layout_centerHorizontal="true"
32. android:text="Resister" />
33.
34. <ProgressBar
35. android:id="@+id/progressBar1"
36. style="?android:attr/progressBarStyleLarge"
37. android:layout_width="wrap_content"
38. android:layout_height="wrap_content"
39. android:layout_alignLeft="@+id/button1"
40. android:layout_below="@+id/editText2"
41. android:layout_marginTop="87dp" />
42.
43. </RelativeLayout>
MainActivity class
File: MainActivity.java
1. package com.example.newrestapi;
2.
3. import java.io.BufferedReader;
4. import java.io.InputStream;
5. import java.io.InputStreamReader;
6. import java.util.ArrayList;
7. import java.util.List;
8. import org.apache.http.HttpEntity;
9. import org.apache.http.HttpResponse;
10. import org.apache.http.NameValuePair;
11. import org.apache.http.client.HttpClient;
12. import org.apache.http.client.entity.UrlEncodedFormEntity;
13. import org.apache.http.client.methods.HttpPost;
14. import org.apache.http.impl.client.DefaultHttpClient;
15. import org.apache.http.message.BasicNameValuePair;
16. import android.os.AsyncTask;
17. import android.os.Bundle;
18. import android.app.Activity;
19. import android.content.Intent;
20. import android.view.View;
21. import android.view.View.OnClickListener;
22. import android.widget.Button;
23. import android.widget.EditText;
24. import android.widget.ProgressBar;
25. import android.widget.Toast;
26.
27. public class MainActivity extends Activity {
28. EditText password,userName;
29. Button login,resister;
30. ProgressBar progressBar;
31.
32.
33.
34. protected void onCreate(Bundle savedInstanceState) {
35. super.onCreate(savedInstanceState);
36. setContentView(R.layout.activity_main);
37. password=(EditText) findViewById(R.id.editText2);
38. userName=(EditText) findViewById(R.id.editText1);
39. login=(Button) findViewById(R.id.button1);
40. resister=(Button) findViewById(R.id.button2);
41.
42. //progess_msz.setVisibility(View.GONE);
43. progressBar=(ProgressBar) findViewById(R.id.progressBar1);
44. progressBar.setVisibility(View.GONE);
45.
46.
47. resister.setOnClickListener(new OnClickListener() {
48.
49. @Override
50. public void onClick(View arg0) {
51. // TODO Auto-generated method stub
52. Intent intent=new Intent(MainActivity.this,ResisterUser.class);
53. startActivity(intent);
54. }
55. });
56. login.setOnClickListener(new OnClickListener() {
57.
58. public void onClick(View v) {
59. progressBar.setVisibility(View.VISIBLE);
60.
61. String s1=userName.getText().toString();
62. String s2=password.getText().toString();
63. new ExecuteTask().execute(s1,s2);
64.
65. }
66. });
67.
68.
69. }
70.
71. class ExecuteTask extends AsyncTask<String, Integer, String>
72. {
73.
74. @Override
75. protected String doInBackground(String... params) {
76.
77. String res=PostData(params);
78.
79. return res;
80. }
81.
82. @Override
83. protected void onPostExecute(String result) {
84. progressBar.setVisibility(View.GONE);
85. //progess_msz.setVisibility(View.GONE);
86. Toast.makeText(getApplicationContext(), result, 3000).show();
87. }
88.
89. }
90.
91. public String PostData(String[] valuse) {
92. String s="";
93. try
94. {
95. HttpClient httpClient=new DefaultHttpClient();
96. HttpPost httpPost=new HttpPost("http://10.0.0.8:7777/HttpPostServlet/servlet/
Login");
97.
98. List<NameValuePair> list=new ArrayList<NameValuePair>();
99. list.add(new BasicNameValuePair("name", valuse[0]));
100. list.add(new BasicNameValuePair("pass",valuse[1]));
101. httpPost.setEntity(new UrlEncodedFormEntity(list));
102. HttpResponse httpResponse= httpClient.execute(httpPost);
103.
104. HttpEntity httpEntity=httpResponse.getEntity();
105. s= readResponse(httpResponse);
106.
107. }
108. catch(Exception exception) {}
109. return s;
110.
111.
112. }
113. public String readResponse(HttpResponse res) {
114. InputStream is=null;
115. String return_text="";
116. try {
117. is=res.getEntity().getContent();
118. BufferedReader bufferedReader=new BufferedReader(new InputStrea
mReader(is));
119. String line="";
120. StringBuffer sb=new StringBuffer();
121. while ((line=bufferedReader.readLine())!=null)
122. {
123. sb.append(line);
124. }
125. return_text=sb.toString();
126. } catch (Exception e)
127. {
128.
129. }
130. return return_text;
131.
132. }
133.
134. }
RegisterUser class
File: RegisterUser.java
1. package com.example.newrestapi;
2.
3. import java.util.ArrayList;
4. import java.util.List;
5. import org.apache.http.NameValuePair;
6. import org.apache.http.client.HttpClient;
7. import org.apache.http.client.entity.UrlEncodedFormEntity;
8. import org.apache.http.client.methods.HttpPost;
9. import org.apache.http.impl.client.DefaultHttpClient;
10. import org.apache.http.message.BasicNameValuePair;
11. import android.os.AsyncTask;
12. import android.os.Bundle;
13. import android.app.Activity;
14. import android.view.View;
15. import android.view.View.OnClickListener;
16. import android.widget.Button;
17. import android.widget.EditText;
18. import android.widget.ProgressBar;
19.
20. public class ResisterUser extends Activity {
21. EditText userName,passwprd;
22. Button resister,login;
23. ProgressBar progressBar;
24. protected void onCreate(Bundle savedInstanceState) {
25. super.onCreate(savedInstanceState);
26. setContentView(R.layout.activity_resister_user);
27. userName=(EditText) findViewById(R.id.editText1);;
28. passwprd=(EditText) findViewById(R.id.editText2);
29. resister=(Button) findViewById(R.id.button1);
30.
31. progressBar=(ProgressBar) findViewById(R.id.progressBar1);
32. progressBar.setVisibility(View.GONE);
33.
34. resister.setOnClickListener(new OnClickListener() {
35.
36. @Override
37. public void onClick(View v) {
38.
39. progressBar.setVisibility(View.VISIBLE);
40.
41. String s1=userName.getText().toString();
42. String s2=passwprd.getText().toString();
43. new ExecuteTask().execute(s1,s2);
44. }
45. });
46.
47.
48.
49.
50. }
51.
52. class ExecuteTask extends AsyncTask<String, Integer, String>
53. {
54.
55. @Override
56. protected String doInBackground(String... params) {
57.
58. PostData(params);
59. return null;
60. }
61.
62. @Override
63. protected void onPostExecute(String result) {
64. progressBar.setVisibility(View.GONE);
65. }
66.
67. }
68.
69.
70.
71. public void PostData(String[] valuse) {
72. try
73. {
74. HttpClient httpClient=new DefaultHttpClient();
75. HttpPost httpPost=new HttpPost(
76. "http://10.0.0.8:7777/HttpPostServlet/servlet/httpPostServlet");
77. List<NameValuePair> list=new ArrayList<NameValuePair>();
78. list.add(new BasicNameValuePair("name", valuse[0]));
79. list.add(new BasicNameValuePair("pass",valuse[1]));
80. httpPost.setEntity(new UrlEncodedFormEntity(list));
81. httpClient.execute(httpPost);
82. }
83. catch(Exception e)
84. {
85. System.out.println(e);
86. }
87.
88. }
89.
90. }
File: AndroidManifest.xml
You need to provide INTERNET permission in AndroidManifest.xml file.
1. package server;
2.
3. import java.io.IOException;
4. import java.io.ObjectOutputStream;
5. import java.sql.Connection;
6. import java.sql.DriverManager;
7. import java.sql.PreparedStatement;
8. import java.sql.ResultSet;
9. import javax.servlet.ServletException;
10. import javax.servlet.http.HttpServlet;
11. import javax.servlet.http.HttpServletRequest;
12. import javax.servlet.http.HttpServletResponse;
13.
14. public class Login extends HttpServlet {
15.
16.
17. public void doGet(HttpServletRequest request, HttpServletResponse respo
nse)
18. throws ServletException, IOException {
19. response.setContentType("text/html");
20.
21. ObjectOutputStream out=new ObjectOutputStream(response.getOutp
utStream());
22.
23. String n=request.getParameter("name");
24. String p=request.getParameter("pass");
25. System.out.println(n);
26. System.out.println(p);
27.
28. if(validate(n, p)){
29. out.writeObject("success");
30.
31. }
32. else{
33. out.writeObject("Sorry username or password error");
34.
35. }
36.
37. out.close();
38. }
39.
40.
41. public static boolean validate(String name,String pass){
42. boolean status=false;
43. try{
44. Class.forName("oracle.jdbc.driver.OracleDriver");
45. Connection con=DriverManager.getConnection(
46. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
47.
48. PreparedStatement ps=con.prepareStatement(
49. "select * from javatpoint_user where name=? and password=?");
50. ps.setString(1,name);
51. ps.setString(2,pass);
52.
53. ResultSet rs=ps.executeQuery();
54. status=rs.next();
55.
56. }catch(Exception e){System.out.println(e);}
57. return status;
58. }
59. public void doPost(HttpServletRequest request,HttpServletResponse respo
nse)
60. throws ServletException, IOException {
61. doGet(request, response);
62.
63. }
64. }
httpPostServlet Servlet class
File: httpPostServlet.java
1. package server;
2.
3. import java.io.IOException;
4. import java.sql.Connection;
5. import java.sql.DriverManager;
6. import java.sql.PreparedStatement;
7. import javax.servlet.ServletException;
8. import javax.servlet.http.HttpServlet;
9. import javax.servlet.http.HttpServletRequest;
10. import javax.servlet.http.HttpServletResponse;
11.
12.
13. public class httpPostServlet extends HttpServlet {
14.
15.
16. public void doGet(HttpServletRequest request,HttpServletResponse response)
17. throws ServletException, IOException {
18. response.setContentType("text/html");
19. String recived_data="";
20.
21.
22. String s1=request.getParameter("name");
23. String s2=request.getParameter("pass");
24. System.out.println(s1);
25. System.out.println(s2);
26.
27. try
28. {
29. Class.forName("oracle.jdbc.driver.OracleDriver");
30. Connection con=DriverManager.getConnection(
31. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
32. PreparedStatement ps=con.prepareStatement(
33. "insert into javatpoint_user(name,password) values(?,?)");
34. ps.setString(1, s1);
35. ps.setString(2,s2);
36. ps.executeUpdate();
37. con.close();
38. }
39. catch (Exception e) {
40. e.printStackTrace();
41. }
42.
43. }
44. public void doPost(HttpServletRequest request,HttpServletResponse response)
45. throws ServletException, IOException {
46. doGet(request, response);
47. }
48.
49. }
index.jsp
1. <form action="servlet/Login">
2. Name:<input type="text" name="name"/><br/>
3. Password:<input type="password" name="pass"/><br/>
4. <input type="submit" value="login"/>
5. </form>
1. Normal: This type of map displays typical road map, natural features like river and
some features build by humans.
2. Hybrid: This type of map displays satellite photograph data with typical road maps. It
also displays road and feature labels.
3. Satellite: Satellite type displays satellite photograph data, but doesn't display road
and feature labels.
4. Terrain: This type displays photographic data. This includes colors, contour lines and
labels and perspective shading.
5. None: This type displays an empty grid with no tiles loaded.
1. googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
2. googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
3. googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
4. googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
Methods of Google map
Google map API provides several methods that help to customize Google map.
These methods are as following:
Methods Description
Paste the copied URL at the browser. It will open the following page.
Click on Create API key to generate API key.
After clicking on Create API key, it will generate our API key displaying the following
screen.
Copy this generated API key in our google_map_api.xml file
activity_maps.xml
1. <fragment xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:map="http://schemas.android.com/apk/res-auto"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:id="@+id/map"
5. android:name="com.google.android.gms.maps.SupportMapFragment"
6. android:layout_width="match_parent"
7. android:layout_height="match_parent"
8. tools:context="example.com.mapexample.MapsActivity" />
MapsActivity.java
To get the GoogleMap object in our MapsActivity.java class we need to implement
the OnMapReadyCallback interface and override the onMapReady() callback method.
1. package example.com.mapexample;
2.
3. import android.support.v4.app.FragmentActivity;
4. import android.os.Bundle;
5. import com.google.android.gms.maps.CameraUpdateFactory;
6. import com.google.android.gms.maps.GoogleMap;
7. import com.google.android.gms.maps.OnMapReadyCallback;
8. import com.google.android.gms.maps.SupportMapFragment;
9. import com.google.android.gms.maps.model.LatLng;
10. import com.google.android.gms.maps.model.MarkerOptions;
11.
12. public class MapsActivity extends FragmentActivity implements OnMapReadyCallba
ck{
13.
14. private GoogleMap mMap;
15.
16. @Override
17. protected void onCreate(Bundle savedInstanceState) {
18. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_maps);
20. // Obtain the SupportMapFragment and get notified when the map is ready to b
e used.
21. SupportMapFragment mapFragment = (SupportMapFragment) getSupp
ortFragmentManager()
22. .findFragmentById(R.id.map);
23. mapFragment.getMapAsync(this);
24.
25. }
26.
27. @Override
28. public void onMapReady(GoogleMap googleMap) {
29. mMap = googleMap;
30.
31. // Add a marker in Sydney and move the camera
32. LatLng sydney = new LatLng(-34, 151);
33. mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in
Sydney"));
34. mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
35.
36. }
37. }
Required Permission
Add the following user-permission in AndroidManifest.xml file.
1. <uses-permission android:nam
e="android.permission.ACCESS_FINE_LOCATION" />
2. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
/>
3. <uses-permission android:name="android.permission.INTERNET" />
AndroidManifest.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="example.com.mapexample">
4. <!--
5. The ACCESS_COARSE/FINE_LOCATION permissions are not required to u
se
6. Google Maps Android API v2, but you must specify either coarse or fine
7. location permissions for the 'MyLocation' functionality.
8. -->
9. <uses-permission android:nam
e="android.permission.ACCESS_FINE_LOCATION" />
10. <uses-permission android:nam
e="android.permission.ACCESS_COARSE_LOCATION" />
11. <uses-permission android:name="android.permission.INTERNET" />
12.
13. <application
14. android:allowBackup="true"
15. android:icon="@mipmap/ic_launcher"
16. android:label="@string/app_name"
17. android:roundIcon="@mipmap/ic_launcher_round"
18. android:supportsRtl="true"
19. android:theme="@style/AppTheme">
20.
21. <meta-data
22. android:name="com.google.android.geo.API_KEY"
23. android:value="@string/google_maps_key" />
24.
25. <activity
26. android:name=".MapsActivity"
27. android:label="@string/title_activity_maps">
28. <intent-filter>
29. <action android:name="android.intent.action.MAIN" />
30.
31. <category android:name="android.intent.category.LAUNCHER" />
32. </intent-filter>
33. </activity>
34. </application>
35.
36. </manifest>
build.gradel
Add the following dependencies in build.gradel file.
1. dependencies {
2. implementation fileTree(dir: 'libs', include: ['*.jar'])
3. implementation 'com.android.support:appcompat-v7:26.1.0'
4. implementation 'com.google.android.gms:play-services-maps:11.8.0'
5. testImplementation 'junit:junit:4.12'
6. androidTestImplementation 'com.android.support.test:runner:1.0.1'
7. androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
8. }
Output
Android Google Map Displaying
Current Location
In the previous tutorial of Android Google Map, we simply displayed the default
coordinates (location) set by the MapsActivity.java class file.
Now in this tutorial we will display and place marker at the user current location. For
doing this we need to generate Google Map API key. The process of generating
Google Map API is described in tutorial Android Google Map.
To display the user current location we need to implements some interfaces and
there callbacks methods.
activity_maps.xml
Add a SupportMapFragment in fragment in activity_maps.xml file.
1. <fragment xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:map="http://schemas.android.com/apk/res-auto"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:id="@+id/map"
5. android:name="com.google.android.gms.maps.SupportMapFragment"
6. android:layout_width="match_parent"
7. android:layout_height="match_parent"
8. tools:context="example.com.mapexample.MapsActivity" />
build.gradel
Add the following dependencies in build.gradel file.
1. dependencies {
2. implementation fileTree(dir: 'libs', include: ['*.jar'])
3. implementation 'com.android.support:appcompat-v7:26.1.0'
4. implementation 'com.google.android.gms:play-services-maps:11.8.0'
5. compile 'com.google.android.gms:play-services-location:11.8.0'
6. testImplementation 'junit:junit:4.12'
7. androidTestImplementation 'com.android.support.test:runner:1.0.1'
8. androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
9.
10. }
MapsActivity.java
Add the following code in MapsActivity.java file.
1. package example.com.mapexample;
2.
3.
4. import android.os.Build;
5. import android.support.v4.app.FragmentActivity;
6. import android.os.Bundle;
7.
8. import com.google.android.gms.common.api.GoogleApiClient;
9. import com.google.android.gms.maps.CameraUpdateFactory;
10. import com.google.android.gms.maps.GoogleMap;
11. import com.google.android.gms.maps.OnMapReadyCallback;
12. import com.google.android.gms.maps.SupportMapFragment;
13. import com.google.android.gms.maps.model.BitmapDescriptorFactory;
14. import com.google.android.gms.maps.model.LatLng;
15. import com.google.android.gms.maps.model.Marker;
16. import com.google.android.gms.maps.model.MarkerOptions;
17. import com.google.android.gms.location.LocationServices;
18.
19. import android.location.Location;
20. import android.Manifest;
21. import android.content.pm.PackageManager;
22. import android.support.v4.content.ContextCompat;
23. import com.google.android.gms.common.ConnectionResult;
24. import com.google.android.gms.location.LocationListener;
25. import com.google.android.gms.location.LocationRequest;
26.
27.
28. public class MapsActivity extends FragmentActivity implements OnMapReadyCallba
ck,
29. LocationListener,GoogleApiClient.ConnectionCallbacks,
30. GoogleApiClient.OnConnectionFailedListener{
31.
32. private GoogleMap mMap;
33. Location mLastLocation;
34. Marker mCurrLocationMarker;
35. GoogleApiClient mGoogleApiClient;
36. LocationRequest mLocationRequest;
37.
38. @Override
39. protected void onCreate(Bundle savedInstanceState) {
40. super.onCreate(savedInstanceState);
41. setContentView(R.layout.activity_maps);
42. // Obtain the SupportMapFragment and get notified when the map is ready to b
e used.
43. SupportMapFragment mapFragment = (SupportMapFragment) getSupp
ortFragmentManager()
44. .findFragmentById(R.id.map);
45. mapFragment.getMapAsync(this);
46.
47. }
48.
49. @Override
50. public void onMapReady(GoogleMap googleMap) {
51. mMap = googleMap;
52.
53. if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
54. if (ContextCompat.checkSelfPermission(this,
55. Manifest.permission.ACCESS_FINE_LOCATION)
56. == PackageManager.PERMISSION_GRANTED) {
57. buildGoogleApiClient();
58. mMap.setMyLocationEnabled(true);
59. }
60. }
61. else {
62. buildGoogleApiClient();
63. mMap.setMyLocationEnabled(true);
64. }
65.
66. }
67. protected synchronized void buildGoogleApiClient() {
68. mGoogleApiClient = new GoogleApiClient.Builder(this)
69. .addConnectionCallbacks(this)
70. .addOnConnectionFailedListener(this)
71. .addApi(LocationServices.API).build();
72. mGoogleApiClient.connect();
73. }
74.
75. @Override
76. public void onConnected(Bundle bundle) {
77.
78. mLocationRequest = new LocationRequest();
79. mLocationRequest.setInterval(1000);
80. mLocationRequest.setFastestInterval(1000);
81. mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_PO
WER_ACCURACY);
82. if (ContextCompat.checkSelfPermission(this,
83. Manifest.permission.ACCESS_FINE_LOCATION)
84. == PackageManager.PERMISSION_GRANTED) {
85. LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleA
piClient, mLocationRequest, this);
86. }
87.
88. }
89.
90. @Override
91. public void onConnectionSuspended(int i) {
92.
93. }
94.
95. @Override
96. public void onLocationChanged(Location location) {
97.
98. mLastLocation = location;
99. if (mCurrLocationMarker != null) {
100. mCurrLocationMarker.remove();
101. }
102. //Place current location marker
103. LatLng latLng = new LatLng(location.getLatitude(), location.getLon
gitude());
104. MarkerOptions markerOptions = new MarkerOptions();
105. markerOptions.position(latLng);
106. markerOptions.title("Current Position");
107. markerOptions.icon(BitmapDescriptorFactory.defaultMarker(Bitma
pDescriptorFactory.HUE_GREEN));
108. mCurrLocationMarker = mMap.addMarker(markerOptions);
109.
110. //move map camera
111. mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
112. mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
113.
114. //stop location updates
115. if (mGoogleApiClient != null) {
116. LocationServices.FusedLocationApi.removeLocationUpdates(mGoogle
ApiClient, this);
117. }
118.
119. }
120.
121. @Override
122. public void onConnectionFailed(ConnectionResult connectionResult) {
123.
124. }
125.
126. }
Request Runtime Permission
Android device having Android 6.0 (Marshmallow) or later are required some
permission at runtime to access device functionality.
1. <uses-permission android:nam
e="android.permission.ACCESS_FINE_LOCATION" />
2. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
/>
3. <uses-permission android:name="android.permission.INTERNET" />
AndroidManifest.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="example.com.mapexample">
4. <!--
5. The ACCESS_COARSE/FINE_LOCATION permissions are not required to u
se
6. Google Maps Android API v2, but you must specify either coarse or fine
7. location permissions for the 'MyLocation' functionality.
8. -->
9. <uses-permission android:nam
e="android.permission.ACCESS_FINE_LOCATION" />
10. <uses-permission android:nam
e="android.permission.ACCESS_COARSE_LOCATION" />
11. <uses-permission android:name="android.permission.INTERNET" />
12.
13.
14. <application
15. android:allowBackup="true"
16. android:icon="@mipmap/ic_launcher"
17. android:label="@string/app_name"
18. android:roundIcon="@mipmap/ic_launcher_round"
19. android:supportsRtl="true"
20. android:theme="@style/AppTheme">
21. <!--
22. The API key for Google Maps-based APIs is defined as a string resource.
23. (See the file "res/values/google_maps_api.xml").
24. Note that the API key is linked to the encryption key used to sign the APK.
25. You need a different API key for each encryption key, including the rel
ease key that is used to
26. sign the APK for publishing.
27. You can define the keys for the debug and release targets in src/
debug/ and src/release/.
28. -->
29. <meta-data
30. android:name="com.google.android.geo.API_KEY"
31. android:value="@string/google_maps_key" />
32.
33. <activity
34. android:name=".MapsActivity"
35. android:label="@string/title_activity_maps">
36. <intent-filter>
37. <action android:name="android.intent.action.MAIN" />
38.
39. <category android:name="android.intent.category.LAUNCHER" />
40. </intent-filter>
41. </activity>
42. </application>
43.
44. </manifest>
Output
Android Google Map Search Location
using Geocoder
In the previous tutorial of Android Google Map and Android Google Map Displaying
Current Location we described about display basic Google Map and current location
respectively.
Now in this tutorial we will implement location search functionality in Google Map.
Searching location in Google Map API is done through Geocoder class. Geocoder
class is used to handle geocoding and reverse geocoding.
Let's see the code which convert location name into coordinate.
activity_maps.xml
Add a fragment (SupportMapFragment), EditText and Button in activity_maps.xml file.
1. <fragment xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:map="http://schemas.android.com/apk/res-auto"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:id="@+id/map"
5. android:name="com.google.android.gms.maps.SupportMapFragment"
6. android:layout_width="match_parent"
7. android:layout_height="match_parent"
8. tools:context="example.com.mapexample.MapsActivity">
9. <LinearLayout
10. android:layout_width="match_parent"
11. android:layout_height="wrap_content"
12. android:orientation="horizontal">
13.
14. <EditText
15. android:layout_width="248dp"
16. android:layout_height="wrap_content"
17. android:id="@+id/editText"
18. android:layout_weight="0.5"
19. android:inputType="textPersonName"
20. android:hint="Search Location" />
21.
22. <Button
23. android:layout_width="wrap_content"
24. android:layout_height="wrap_content"
25. android:layout_weight="0.5"
26. android:onClick="searchLocation"
27. android:text="Search" />
28.
29. </LinearLayout>
30.
31. </fragment>
build.gradel
Add the following dependencies in build.gradel file.
1. dependencies {
2. implementation fileTree(dir: 'libs', include: ['*.jar'])
3. implementation 'com.android.support:appcompat-v7:26.1.0'
4. implementation 'com.google.android.gms:play-services-maps:11.8.0'
5. compile 'com.google.android.gms:play-services-location:11.8.0'
6. testImplementation 'junit:junit:4.12'
7. androidTestImplementation 'com.android.support.test:runner:1.0.1'
8. androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
9.
10. }
MapsActivity.java
Add the following code in MapsActivity.java file.
1. package example.com.mapexample;
2.
3. import android.location.Address;
4. import android.location.Geocoder;
5. import android.os.Build;
6. import android.support.v4.app.FragmentActivity;
7. import android.os.Bundle;
8.
9. import com.google.android.gms.common.api.GoogleApiClient;
10. import com.google.android.gms.maps.CameraUpdateFactory;
11. import com.google.android.gms.maps.GoogleMap;
12. import com.google.android.gms.maps.OnMapReadyCallback;
13. import com.google.android.gms.maps.SupportMapFragment;
14. import com.google.android.gms.maps.model.BitmapDescriptorFactory;
15. import com.google.android.gms.maps.model.LatLng;
16. import com.google.android.gms.maps.model.Marker;
17. import com.google.android.gms.maps.model.MarkerOptions;
18. import com.google.android.gms.location.LocationServices;
19.
20. import android.location.Location;
21. import android.Manifest;
22. import android.content.pm.PackageManager;
23. import android.support.v4.content.ContextCompat;
24. import android.view.View;
25. import android.widget.EditText;
26. import android.widget.Toast;
27.
28. import com.google.android.gms.common.ConnectionResult;
29. import com.google.android.gms.location.LocationListener;
30. import com.google.android.gms.location.LocationRequest;
31.
32. import java.io.IOException;
33. import java.util.List;
34.
35.
36. public class MapsActivity extends FragmentActivity implements OnMapReadyCallba
ck,
37. LocationListener,GoogleApiClient.ConnectionCallbacks,
38. GoogleApiClient.OnConnectionFailedListener{
39.
40. private GoogleMap mMap;
41. Location mLastLocation;
42. Marker mCurrLocationMarker;
43. GoogleApiClient mGoogleApiClient;
44. LocationRequest mLocationRequest;
45.
46. @Override
47. protected void onCreate(Bundle savedInstanceState) {
48. super.onCreate(savedInstanceState);
49. setContentView(R.layout.activity_maps);
50. // Obtain the SupportMapFragment and get notified when the map is ready to b
e used.
51. SupportMapFragment mapFragment = (SupportMapFragment) getSupp
ortFragmentManager()
52. .findFragmentById(R.id.map);
53. mapFragment.getMapAsync(this);
54.
55. }
56.
57. @Override
58. public void onMapReady(GoogleMap googleMap) {
59. mMap = googleMap;
60.
61. if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
62. if (ContextCompat.checkSelfPermission(this,
63. Manifest.permission.ACCESS_FINE_LOCATION)
64. == PackageManager.PERMISSION_GRANTED) {
65. buildGoogleApiClient();
66. mMap.setMyLocationEnabled(true);
67. }
68. }
69. else {
70. buildGoogleApiClient();
71. mMap.setMyLocationEnabled(true);
72. }
73.
74. }
75. protected synchronized void buildGoogleApiClient() {
76. mGoogleApiClient = new GoogleApiClient.Builder(this)
77. .addConnectionCallbacks(this)
78. .addOnConnectionFailedListener(this)
79. .addApi(LocationServices.API).build();
80. mGoogleApiClient.connect();
81. }
82.
83. @Override
84. public void onConnected(Bundle bundle) {
85.
86. mLocationRequest = new LocationRequest();
87. mLocationRequest.setInterval(1000);
88. mLocationRequest.setFastestInterval(1000);
89. mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_PO
WER_ACCURACY);
90. if (ContextCompat.checkSelfPermission(this,
91. Manifest.permission.ACCESS_FINE_LOCATION)
92. == PackageManager.PERMISSION_GRANTED) {
93. LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleA
piClient, mLocationRequest, this);
94. }
95.
96. }
97.
98. @Override
99. public void onConnectionSuspended(int i) {
100.
101. }
102.
103. @Override
104. public void onLocationChanged(Location location) {
105.
106. mLastLocation = location;
107. if (mCurrLocationMarker != null) {
108. mCurrLocationMarker.remove();
109. }
110. //Place current location marker
111. LatLng latLng = new LatLng(location.getLatitude(), location.getLon
gitude());
112. MarkerOptions markerOptions = new MarkerOptions();
113. markerOptions.position(latLng);
114. markerOptions.title("Current Position");
115. markerOptions.icon(BitmapDescriptorFactory.defaultMarker(Bitma
pDescriptorFactory.HUE_GREEN));
116. mCurrLocationMarker = mMap.addMarker(markerOptions);
117.
118. //move map camera
119. mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
120. mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
121.
122. //stop location updates
123. if (mGoogleApiClient != null) {
124. LocationServices.FusedLocationApi.removeLocationUpdates(mGoogle
ApiClient, this);
125. }
126.
127. }
128.
129. @Override
130. public void onConnectionFailed(ConnectionResult connectionResult) {
131.
132. }
133.
134. public void searchLocation(View view) {
135. EditText locationSearch = (EditText) findViewById(R.id.editText);
136. String location = locationSearch.getText().toString();
137. List<Address> addressList = null;
138.
139. if (location != null || !location.equals("")) {
140. Geocoder geocoder = new Geocoder(this);
141. try {
142. addressList = geocoder.getFromLocationName(location, 1);
143.
144. } catch (IOException e) {
145. e.printStackTrace();
146. }
147. Address address = addressList.get(0);
148. LatLng latLng = new LatLng(address.getLatitude(), address.getLongitu
de());
149. mMap.addMarker(new MarkerOptions().position(latLng).title(loc
ation));
150. mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
151. Toast.makeText(getApplicationContext(),address.getLatitude()+"
"+address.getLongitude(),Toast.LENGTH_LONG).show();
152. }
153. }
154.
155. }
Required Permission in AndroidManifest.xml
Add the following user-permission in AndroidManifest.xml file.
1. <uses-permission android:nam
e="android.permission.ACCESS_FINE_LOCATION" />
2. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
/>
3. <uses-permission android:name="android.permission.INTERNET" />
AndroidManifest.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="example.com.mapexample">
4. <!--
5. The ACCESS_COARSE/FINE_LOCATION permissions are not required to u
se
6. Google Maps Android API v2, but you must specify either coarse or fine
7. location permissions for the 'MyLocation' functionality.
8. -->
9. <uses-permission android:nam
e="android.permission.ACCESS_FINE_LOCATION" />
10. <uses-permission android:nam
e="android.permission.ACCESS_COARSE_LOCATION" />
11. <uses-permission android:name="android.permission.INTERNET" />
12.
13. <application
14. android:allowBackup="true"
15. android:icon="@mipmap/ic_launcher"
16. android:label="@string/app_name"
17. android:roundIcon="@mipmap/ic_launcher_round"
18. android:supportsRtl="true"
19. android:theme="@style/AppTheme">
20. <!--
21. The API key for Google Maps-based APIs is defined as a string resourc
e.
22. (See the file "res/values/google_maps_api.xml").
23. Note that the API key is linked to the encryption key used to sign the
APK.
24. You need a different API key for each encryption key, including the release ke
y that is used to
25. sign the APK for publishing.
26. You can define the keys for the debug and release targets in src/debug/ and s
rc/release/.
27. -->
28. <meta-data
29. android:name="com.google.android.geo.API_KEY"
30. android:value="@string/google_maps_key" />
31.
32. <activity
33. android:name=".MapsActivity"
34. android:label="@string/title_activity_maps">
35. <intent-filter>
36. <action android:name="android.intent.action.MAIN" />
37.
38. <category android:name="android.intent.category.LAUNCHER" />
39. </intent-filter>
40. </activity>
41. </application>
42.
43. </manifest>
Output
Android SQLite Tutorial
SQLite is an open-source relational database i.e. used to perform database
operations on android devices such as storing, manipulating or retrieving persistent
data from the database.
Here, we are going to see the example of sqlite to store and fetch the data. Data is
displayed in the logcat. For displaying data on the spinner or listview, move to the
next page.
SQLiteOpenHelper class
The android.database.sqlite.SQLiteOpenHelper class is used for database creation
and version management. For performing any database operation, you have to
provide the implementation of onCreate() and onUpgrade() methods of
SQLiteOpenHelper class.
Constructor Description
There are many methods in SQLiteOpenHelper class. Some of them are as follows:
Method Description
public abstract void onCreate(SQLiteDatabase db) called only once when database
is created for the first time.
SQLiteDatabase class
It contains methods to be performed on sqlite database such as create, update,
delete, select etc.
There are many methods in SQLiteDatabase class. Some of them are as follows:
Method Description
void execSQL(String sql) executes the sql query not select query.
long insert(String table, String inserts a record on the database. The table
nullColumnHack, ContentValues specifies the table name, nullColumnHack doesn't
values) allow completely null values. If second argument is
null, android will store null values if values are
empty. The third argument specifies the values to
be stored.
File: Contact.java
1. package example.javatpoint.com.sqlitetutorial;
2.
3. public class Contact {
4. int _id;
5. String _name;
6. String _phone_number;
7. public Contact(){ }
8. public Contact(int id, String name, String _phone_number){
9. this._id = id;
10. this._name = name;
11. this._phone_number = _phone_number;
12. }
13.
14. public Contact(String name, String _phone_number){
15. this._name = name;
16. this._phone_number = _phone_number;
17. }
18. public int getID(){
19. return this._id;
20. }
21.
22. public void setID(int id){
23. this._id = id;
24. }
25.
26. public String getName(){
27. return this._name;
28. }
29.
30. public void setName(String name){
31. this._name = name;
32. }
33.
34. public String getPhoneNumber(){
35. return this._phone_number;
36. }
37.
38. public void setPhoneNumber(String phone_number){
39. this._phone_number = phone_number;
40. }
41. }
File: DatabaseHandler.java
Now, let's create the database handler class that extends SQLiteOpenHelper class
and provides the implementation of its methods.
1. package example.javatpoint.com.sqlitetutorial;
2.
3. import android.content.ContentValues;
4. import android.content.Context;
5. import android.database.Cursor;
6. import android.database.sqlite.SQLiteDatabase;
7. import android.database.sqlite.SQLiteOpenHelper;
8. import java.util.ArrayList;
9. import java.util.List;
10.
11.
12. public class DatabaseHandler extends SQLiteOpenHelper {
13. private static final int DATABASE_VERSION = 1;
14. private static final String DATABASE_NAME = "contactsManager";
15. private static final String TABLE_CONTACTS = "contacts";
16. private static final String KEY_ID = "id";
17. private static final String KEY_NAME = "name";
18. private static final String KEY_PH_NO = "phone_number";
19.
20. public DatabaseHandler(Context context) {
21. super(context, DATABASE_NAME, null, DATABASE_VERSION);
22. //3rd argument to be passed is CursorFactory instance
23. }
24.
25. // Creating Tables
26. @Override
27. public void onCreate(SQLiteDatabase db) {
28. String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
29. + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
30. + KEY_PH_NO + " TEXT" + ")";
31. db.execSQL(CREATE_CONTACTS_TABLE);
32. }
33.
34. // Upgrading database
35. @Override
36. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
37. // Drop older table if existed
38. db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
39.
40. // Create tables again
41. onCreate(db);
42. }
43.
44. // code to add the new contact
45. void addContact(Contact contact) {
46. SQLiteDatabase db = this.getWritableDatabase();
47.
48. ContentValues values = new ContentValues();
49. values.put(KEY_NAME, contact.getName()); // Contact Name
50. values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
51.
52. // Inserting Row
53. db.insert(TABLE_CONTACTS, null, values);
54. //2nd argument is String containing nullColumnHack
55. db.close(); // Closing database connection
56. }
57.
58. // code to get the single contact
59. Contact getContact(int id) {
60. SQLiteDatabase db = this.getReadableDatabase();
61.
62. Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
63. KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
64. new String[] { String.valueOf(id) }, null, null, null, null);
65. if (cursor != null)
66. cursor.moveToFirst();
67.
68. Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
69. cursor.getString(1), cursor.getString(2));
70. // return contact
71. return contact;
72. }
73.
74. // code to get all contacts in a list view
75. public List<Contact> getAllContacts() {
76. List<Contact> contactList = new ArrayList<Contact>();
77. // Select All Query
78. String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
79.
80. SQLiteDatabase db = this.getWritableDatabase();
81. Cursor cursor = db.rawQuery(selectQuery, null);
82.
83. // looping through all rows and adding to list
84. if (cursor.moveToFirst()) {
85. do {
86. Contact contact = new Contact();
87. contact.setID(Integer.parseInt(cursor.getString(0)));
88. contact.setName(cursor.getString(1));
89. contact.setPhoneNumber(cursor.getString(2));
90. // Adding contact to list
91. contactList.add(contact);
92. } while (cursor.moveToNext());
93. }
94.
95. // return contact list
96. return contactList;
97. }
98.
99. // code to update the single contact
100. public int updateContact(Contact contact) {
101. SQLiteDatabase db = this.getWritableDatabase();
102.
103. ContentValues values = new ContentValues();
104. values.put(KEY_NAME, contact.getName());
105. values.put(KEY_PH_NO, contact.getPhoneNumber());
106.
107. // updating row
108. return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
109. new String[] { String.valueOf(contact.getID()) });
110. }
111.
112. // Deleting single contact
113. public void deleteContact(Contact contact) {
114. SQLiteDatabase db = this.getWritableDatabase();
115. db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
116. new String[] { String.valueOf(contact.getID()) });
117. db.close();
118. }
119.
120. // Getting contacts Count
121. public int getContactsCount() {
122. String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
123. SQLiteDatabase db = this.getReadableDatabase();
124. Cursor cursor = db.rawQuery(countQuery, null);
125. cursor.close();
126.
127. // return count
128. return cursor.getCount();
129. }
130.
131. }
File: MainActivity.java
1. package example.javatpoint.com.sqlitetutorial;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5. import android.util.Log;
6. import java.util.List;
7.
8. public class MainActivity extends AppCompatActivity {
9.
10. @Override
11. protected void onCreate(Bundle savedInstanceState) {
12. super.onCreate(savedInstanceState);
13. setContentView(R.layout.activity_main);
14. DatabaseHandler db = new DatabaseHandler(this);
15.
16. // Inserting Contacts
17. Log.d("Insert: ", "Inserting ..");
18. db.addContact(new Contact("Ravi", "9100000000"));
19. db.addContact(new Contact("Srinivas", "9199999999"));
20. db.addContact(new Contact("Tommy", "9522222222"));
21. db.addContact(new Contact("Karthik", "9533333333"));
22.
23. // Reading all contacts
24. Log.d("Reading: ", "Reading all contacts..");
25. List<Contact> contacts = db.getAllContacts();
26.
27. for (Contact cn : contacts) {
28. String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " +
29. cn.getPhoneNumber();
30. // Writing Contacts to log
31. Log.d("Name: ", log);
32. }
33. }
34. }
Output:
activity_main.xml
File: activity_main.xml
Activity class
File: MainActivity.java
1. package example.javatpoint.com.sqlitespinner;
2.
3. import android.content.Context;
4. import android.support.v7.app.AppCompatActivity;
5. import android.os.Bundle;
6. import android.view.View;
7. import android.view.inputmethod.InputMethodManager;
8. import android.widget.AdapterView;
9. import android.widget.ArrayAdapter;
10. import android.widget.Button;
11. import android.widget.EditText;
12. import android.widget.Spinner;
13. import android.widget.Toast;
14. import java.util.List;
15.
16. public class MainActivity extends AppCompatActivity implements AdapterView.OnIt
emSelectedListener {
17. Spinner spinner;
18. Button btnAdd;
19. EditText inputLabel;
20. @Override
21. protected void onCreate(Bundle savedInstanceState) {
22. super.onCreate(savedInstanceState);
23. setContentView(R.layout.activity_main);
24. spinner = findViewById(R.id.spinner);
25. btnAdd = findViewById(R.id.btn_add);
26. inputLabel = findViewById(R.id.input_label);
27.
28. spinner.setOnItemSelectedListener(this);
29.
30. // Loading spinner data from database
31. loadSpinnerData();
32.
33. btnAdd.setOnClickListener(new View.OnClickListener() {
34.
35. @Override
36. public void onClick(View arg0) {
37. String label = inputLabel.getText().toString();
38.
39. if (label.trim().length() > 0) {
40. DatabaseHandler db = new DatabaseHandler(getApplicationContext());
41. db.insertLabel(label);
42.
43. // making input filed text to blank
44. inputLabel.setText("");
45.
46. // Hiding the keyboard
47. InputMethodManager imm = (InputMethodManager)
48. getSystemService(Context.INPUT_METHOD_SERVICE);
49. imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0)
;
50. // loading spinner with newly added data
51. loadSpinnerData();
52. } else {
53. Toast.makeText(getApplicationContext(), "Please enter label name
",
54. Toast.LENGTH_SHORT).show();
55. }
56.
57. }
58. });
59. }
60.
61. /**
62. * Function to load the spinner data from SQLite database
63. * */
64. private void loadSpinnerData() {
65. DatabaseHandler db = new DatabaseHandler(getApplicationContext());
66. List<String> labels = db.getAllLabels();
67.
68. // Creating adapter for spinner
69. ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,an
droid.R.layout.simple_spinner_item, labels);
70.
71. // Drop down layout style - list view with radio button
72. dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropd
own_item);
73.
74. // attaching data adapter to spinner
75. spinner.setAdapter(dataAdapter);
76. }
77.
78. @Override
79. public void onItemSelected(AdapterView<?> parent, View view, int positio
n,
80. long id) {
81. // On selecting a spinner item
82. String label = parent.getItemAtPosition(position).toString();
83.
84. // Showing selected spinner item
85. Toast.makeText(parent.getContext(), "You selected: " + label,
86. Toast.LENGTH_LONG).show();
87.
88. }
89.
90. @Override
91. public void onNothingSelected(AdapterView<?> arg0) {
92. // TODO Auto-generated method stub
93.
94. }
95. }
DatabaseHandler class
File: DatabaseHandler.java
1. package example.javatpoint.com.sqlitespinner;
2.
3. import android.content.ContentValues;
4. import android.content.Context;
5. import android.database.Cursor;
6. import android.database.sqlite.SQLiteDatabase;
7. import android.database.sqlite.SQLiteOpenHelper;
8. import java.util.ArrayList;
9. import java.util.List;
10.
11. public class DatabaseHandler extends SQLiteOpenHelper {
12. private static final int DATABASE_VERSION = 1;
13. private static final String DATABASE_NAME = "spinnerExample";
14. private static final String TABLE_NAME = "labels";
15. private static final String COLUMN_ID = "id";
16. private static final String COLUMN_NAME = "name";
17.
18. public DatabaseHandler(Context context) {
19. super(context, DATABASE_NAME, null, DATABASE_VERSION);
20. }
21.
22. // Creating Tables
23. @Override
24. public void onCreate(SQLiteDatabase db) {
25. // Category table create query
26. String CREATE_ITEM_TABLE = "CREATE TABLE " + TABLE_NAME + "("
27. + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " T
EXT)";
28. db.execSQL(CREATE_ITEM_TABLE);
29. }
30.
31. // Upgrading database
32. @Override
33. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
34. // Drop older table if existed
35. db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
36.
37. // Create tables again
38. onCreate(db);
39. }
40.
41. /**
42. * Inserting new lable into lables table
43. * */
44. public void insertLabel(String label){
45. SQLiteDatabase db = this.getWritableDatabase();
46.
47. ContentValues values = new ContentValues();
48. values.put(COLUMN_NAME, label);//column name, column value
49.
50. // Inserting Row
51. db.insert(TABLE_NAME, null, values);//tableName, nullColumnHack, Cote
ntValues
52. db.close(); // Closing database connection
53. }
54.
55. /**
56. * Getting all labels
57. * returns list of labels
58. * */
59. public List<String> getAllLabels(){
60. List<String> list = new ArrayList<String>();
61.
62. // Select All Query
63. String selectQuery = "SELECT * FROM " + TABLE_NAME;
64.
65. SQLiteDatabase db = this.getReadableDatabase();
66. Cursor cursor = db.rawQuery(selectQuery, null);//
selectQuery,selectedArguments
67.
68. // looping through all rows and adding to list
69. if (cursor.moveToFirst()) {
70. do {
71. list.add(cursor.getString(1));//adding 2nd column data
72. } while (cursor.moveToNext());
73. }
74. // closing connection
75. cursor.close();
76. db.close();
77. // returning lables
78. return list;
79. }
80. }