Android Restful Web Service Tutorial
Android Restful Web Service Tutorial
Creating web service application in android is not a difficult task. We can easily create a
restful web service application in android to authenticate or save information into the
external database such as oracle, mysql, postgre sql, sql server using other application
developed in java, .net, php etc languages. That is what we are going to do.
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 InputStreamRea
der(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
Output:
Java Servlet Login and Register example using oracle
database
Create table javatpoint_user in the oracle database having three columns id, name and
password. Id must be primary key and generated through SEQUENCE.
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 response)
60. throws ServletException, IOException {
61. doGet(request, response);
62.
63. }
64. }
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>
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
You need to have a view only.
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 drawable 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. <?xml version="1.0" encoding="utf-8"?>
2. <animation-list xmlns:android="http://schemas.android.com/apk/res/android"
3. android:oneshot="false">
4.
5. <item android:drawable="@drawable/frame0" android:duration="120" />
6. <item android:drawable="@drawable/frame1" android:duration="120" />
7. <item android:drawable="@drawable/frame2" android:duration="120" />
8. <item android:drawable="@drawable/frame3" android:duration="120" />
9. <item android:drawable="@drawable/frame4" android:duration="120" />
10. <item android:drawable="@drawable/frame5" android:duration="120" />
11. <item android:drawable="@drawable/frame6" android:duration="120" />
12. <item android:drawable="@drawable/frame7" android:duration="120" />
13. <item android:drawable="@drawable/frame8" android:duration="120" />
14. <item android:drawable="@drawable/frame9" android:duration="120" />
15. <item android:drawable="@drawable/frame10" android:duration="120" />
16. <item android:drawable="@drawable/frame11" android:duration="120" />
17. <item android:drawable="@drawable/frame12" android:duration="120" />
18. <item android:drawable="@drawable/frame13" android:duration="120" />
19. <item android:drawable="@drawable/frame14" android:duration="120" />
20. <item android:drawable="@drawable/frame14" android:duration="120" />
21. <item android:drawable="@drawable/frame13" android:duration="120" />
22. <item android:drawable="@drawable/frame12" android:duration="120" />
23. <item android:drawable="@drawable/frame11" android:duration="120" />
24. <item android:drawable="@drawable/frame10" android:duration="120" />
25. <item android:drawable="@drawable/frame9" android:duration="120" />
26. <item android:drawable="@drawable/frame8" android:duration="120" />
27. <item android:drawable="@drawable/frame7" android:duration="120" />
28. <item android:drawable="@drawable/frame6" android:duration="120" />
29. <item android:drawable="@drawable/frame5" android:duration="120" />
30. <item android:drawable="@drawable/frame4" android:duration="120" />
31. <item android:drawable="@drawable/frame3" android:duration="120" />
32. <item android:drawable="@drawable/frame2" android:duration="120" />
33. <item android:drawable="@drawable/frame1" android:duration="120" />
34. <item android:drawable="@drawable/frame0" android:duration="120" />
35.
36. </animation-list>
Output:
Android Sensor Tutorial
Sensors can be used to monitor the three-dimensional device movement or change in the
environment of the device.
Types of Sensors
Android supports three types of sensors:
1) Motion Sensors
These are used to measure acceleration forces and rotational forces along with three axes.
2) Position Sensors
These are used to measure the physical position of device.
3) Environmental Sensors
These are used to measure the environmental changes such as temperature, humidity etc.
1) SensorManager class
The android.hardware.SensorManager class provides methods :
You can get the instance of SensorManager by calling the method getSystemService() and
passing the SENSOR_SERVICE constant in it.
1. SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
2) Sensor class
The android.hardware.Sensor class provides methods to get information of the sensor
such as sensor name, sensor type, sensor resolution, sensor type etc.
3) SensorEvent class
Its instance is created by the system. It provides information about the sensor.
4) SensorEventListener interface
It provides two call back methods to get information when sensor values (x,y and z) change
or sensor accuracy changes.
1. A sensor example that prints x, y and z axis values. Here, we are going to see that.
2. A sensor example that changes the background color when device is shuffled. Click
for changing background color of activity sensor example
activity_main.xml
There is only one textview in this file.
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_NOR
MAL);
37. }else{
38. Toast.makeText(getBaseContext(), "Error: No Accelerometer.", Toast.LENGTH_LON
G).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:
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.
Android fragment lifecycle is affected by activity lifecycle because fragments are included in
activity.
Each fragment has its own life cycle methods that is affected by activity life cycle because
fragments are embedded in activity.
activity_main.xml
File: activity_main.xml
1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. android:layout_width="fill_parent"
3. android:layout_height="fill_parent" >
4.
5. <fragment
6. android:id="@+id/fragment2"
7. android:name="com.example.fragmentexample.Fragment2"
8. android:layout_width="0px"
9. android:layout_height="match_parent"
10. android:layout_weight="1"
11. />
12.
13. <fragment
14. android:id="@+id/fragment1"
15. android:name="com.example.fragmentexample.Fragment1"
16. android:layout_width="0px"
17. android:layout_height="match_parent"
18. android:layout_weight="1"
19. />
20.
21. </LinearLayout>
File: fragment1.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:orientation="vertical"
6. android:background="#00ff00"
7. >
8.
9. <TextView
10. android:id="@+id/textView1"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:text="fragment frist"
14. android:textAppearance="?android:attr/textAppearanceLarge" />
15.
16. </LinearLayout>
File: fragment2.xml
1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:orientation="vertical"
6. android:background="#0000ff"
7. >
8.
9. <TextView
10. android:id="@+id/textView1"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:text="Second Fragment"
14. android:textAppearance="?android:attr/textAppearanceLarge" />
15.
16. </LinearLayout>
MainActivity class
File: MainActivity.java
1. package com.example.fragmentexample;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
5. import android.view.Menu;
6. public class MainActivity extends Activity {
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 com.example.fragmentexample;
2.
3. import android.app.Fragment;
4. import android.os.Bundle;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class Fragment1 extends Fragment {
10. @Override
11. public View onCreateView(LayoutInflater inflater, ViewGroup container,
12. Bundle savedInstanceState) {
13. // TODO Auto-generated method stub
14. return inflater.inflate(R.layout.fragment1,container, false);
15. }
16.
17. }
File: Fragment2.java
1. package com.example.fragmentexample;
2.
3. import android.app.Fragment;
4. import android.os.Bundle;
5. import android.view.LayoutInflater;
6. import android.view.View;
7. import android.view.ViewGroup;
8.
9. public class Fragment2 extends Fragment {
10.
11. public View onCreateView(LayoutInflater inflater, ViewGroup container,
12. Bundle savedInstanceState) {
13. // TODO Auto-generated method stub
14. return inflater.inflate(R.layout.fragment2,container, false);
15. }
16.
17. }
Output:
Android Screen Orientation Example
The screenOrientation is the attribute of activity element. The orientation of android
activity can be portrait, landscape, sensor, unspecified etc. You need to define it in the
AndroidManifest.xml file. For example:
1. <activity
2. android:name="com.example.screenorientation.MainActivity"
3. android:label="@string/app_name"
4. android:screenOrientation="landscape"
5. >
Value Description
unspecified It is the default value. In such case, system chooses the orientation.
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_marginLeft="66dp"
16. android:layout_marginTop="73dp"
17. android:text="Button"
18. android:onClick="onClick"
19. />
20.
21. <EditText
22. android:id="@+id/editText1"
23. android:layout_width="wrap_content"
24. android:layout_height="wrap_content"
25. android:layout_centerHorizontal="true"
26. android:ems="10" />
27.
28. </RelativeLayout>
Activity class
File: MainActivity.java
1. package com.example.f;
2.
3. import android.os.Bundle;
4. import android.app.Activity;
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.
11. public class MainActivity 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_main);
18.
19. editText1=(EditText)findViewById(R.id.editText1);
20. button1=(Button)findViewById(R.id.button1);
21. }
22. public void onClick(View v) {
23. editText1.setText("O android");
24. }
25. }
AndroidManifest.xml
File: AndroidManifest.xml
Output: