Sie sind auf Seite 1von 38

Android 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.

Android Restful Web Service Tutorial


Before developing web services application, you must have basic knowledge of SOAP and
Restful web services. That is why, we are going to discuss basic points about web services
such as what is web service and brief information about SOAP and Restful web services.

What is Web Service?


A web service is a standard for exchanging information between different types of
applications irrespective of language and platform. For example, an android application can
interact with java or .net application using web services.

Android Restful Web Service Example


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. <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 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

You need to provide INTERNET permission in AndroidManifest.xml file.

1. <?xml version="1.0" encoding="utf-8"?>


2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. package="com.example.newrestapi"
4. android:versionCode="1"
5. android:versionName="1.0" >
6.
7. <uses-sdk
8. android:minSdkVersion="8"
9. android:targetSdkVersion="17" />
10.
11. <uses-permission android:name="android.permission.INTERNET" />
12.
13. <application
14. android:allowBackup="true"
15. android:icon="@drawable/ic_launcher"
16. android:label="@string/app_name"
17. android:theme="@style/AppTheme" >
18. <activity
19. android:name="com.example.newrestapi.MainActivity"
20. android:label="@string/app_name" >
21. <intent-filter>
22. <action android:name="android.intent.action.MAIN" />
23.
24. <category android:name="android.intent.category.LAUNCHER" />
25. </intent-filter>
26. </activity>
27. <activity
28. android:name="com.example.newrestapi.ResisterUser"
29. android:label="@string/title_activity_resister_user" >
30. </activity>
31. </application>
32.
33. </manifest>

download this android example

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.

1. CREATE TABLE "JAVATPOINT_USER"


2. ( "ID" NUMBER,
3. "NAME" VARCHAR2(4000),
4. "PASSWORD" VARCHAR2(4000),
5. CONSTRAINT "JAVATPOINT_USER_PK" PRIMARY KEY ("ID") ENABLE
6. )
7. /

New create two servlet classes to login and register user.

Login Servlet class


File: Login.java
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 response)
18. throws ServletException, IOException {
19. response.setContentType("text/html");
20.
21. ObjectOutputStream out=new ObjectOutputStream(response.getOutputStream());

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. }

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>
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.

Let's have a look at the simple example of android 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

Have a image view only.

1. <?xml version="1.0" encoding="utf-8"?>


2. <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. android:id="@+id/anm"
6. >
7.
8. </ImageView>

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 create animation.xml file inside res/drawable-hdpi directory.

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>

download this android example

Output:
Android Sensor Tutorial
Sensors can be used to monitor the three-dimensional device movement or change in the
environment of the device.

Android provides sensor api to work with different types of sensors.

Types of Sensors
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.

Android Sensor API


Android sensor api provides many classes and interface. The important classes and
interfaces of sensor api are as follows:

1) SensorManager class
The android.hardware.SensorManager class provides methods :

o to get sensor instance,

o to access and list sensors,

o to register and unregister sensor listeners etc.

You can get the instance of SensorManager by calling the method getSystemService() and
passing the SENSOR_SERVICE constant in it.

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.

Public and abstract methods Description

void onAccuracyChanged(Sensor sensor, int accuracy) it is called when sensor accurac


void onSensorChanged(SensorEvent event) it is called when sensor values a

Android simple sensor app example


Let's see the two sensor examples.

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. }

download this android example

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.

The FragmentManager class is responsible to make interaction between fragment objects.

Android Fragment Lifecycle


The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle methods
for fragment.

No. Method Description

1) onAttach(Activity) it is called only once when it is attached with activ

2) onCreate(Bundle) It is used to initialize the fragment.

3) onCreateView(LayoutInflater, creates and returns view hierarchy.


ViewGroup, Bundle)

4) onActivityCreated(Bundle) It is invoked after the completion of onCreate() m

5) onViewStateRestored(Bundle) It provides information to the fragment that all


fragment view hierarchy has been restored.

6) onStart() makes the fragment visible.

7) onResume() makes the fragment interactive.

8) onPause() is called when fragment is no longer interactive.

9) onStop() is called when fragment is no longer visible.

10) onDestroyView() allows the fragment to clean up resources.


11) onDestroy() allows the fragment to do final clean up of fragme

12) onDetach() It is called immediately prior to the fragment


associated with its activity.

Android Fragment Example


Let's have a look at the simple example of android fragment.

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. }

download android fragment example

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. >

The common values for screenOrientation attribute are as follows:

Value Description

unspecified It is the default value. In such case, system chooses the orientation.

portrait taller not wider

landscape wider not taller

sensor orientation is determined by the device orientation sensor.

Android landscape mode screen orientation example


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. <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

1. <?xml version="1.0" encoding="utf-8"?>


2. <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
3. package="com.example.screenorientation"
4. android:versionCode="1"
5. android:versionName="1.0" >
6.
7. <uses-sdk
8. android:minSdkVersion="8"
9. android:targetSdkVersion="16" />
10.
11. <application
12. android:allowBackup="true"
13. android:icon="@drawable/ic_launcher"
14. android:label="@string/app_name"
15. android:theme="@style/AppTheme" >
16. <activity
17. android:name="com.example.screenorientation.MainActivity"
18. android:label="@string/app_name"
19. android:screenOrientation="landscape"
20. >
21. <intent-filter>
22. <action android:name="android.intent.action.MAIN" />
23.
24. <category android:name="android.intent.category.LAUNCHER" />
25. </intent-filter>
26. </activity>
27. </application>
28.
29. </manifest>

download this android example

Output:

Das könnte Ihnen auch gefallen