The document describes the process of creating an Android application to retrieve and display temperature data from a web service. It includes:
1. Creating layout files (activity_main.xml and activity_sensor_value.xml) to define the user interface for two screens - one to enter the web service address and another to display the retrieved data.
2. Adding Java classes (MainActivity.java and SensorValue.java) to handle user input, make HTTP requests to the web service, parse the XML response, and update the display.
3. Configuring the AndroidManifest.xml file and adding necessary permissions to declare app components and functionality.
The app allows users to enter a web service address
Best VIP Call Girls Noida Sector 44 Call Me: 8448380779
Â
Create an Android App to Display Data from a Web Service
1. HĂžgskolen i Telemark
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Faculty of Technology, Postboks 203, KjĂžlnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01
Android Programming
Android App
Cuong Nguyen, 2013.06.19
2. 2
Table of Contents
Introduction............................................................................................................................................. 3
1 Technical Implementation.............................................................................................................. 4
1.1 CreateAndroid WebService client ........................................................................................... 4
1.2 Android programming............................................................................................................. 6
1.3 Execute and run the app ....................................................................................................... 14
1.4 Comments & explainations ................................................................................................... 15
3. 3
1Introduction
This tutorial will focus on how to create a Web Service Client to exchange data with a Web Service.
The Web Service which was created earlier to broad cast temperature data, here we will create an
Android âNativeâ application to present the published data in an appropriate manner on Android
device. In able to complete this tutorial you should already have a deployed Web Service running to
test the creating Android Web Service client. If you do not have a Web Service yet, it is
recommended to go through the âWebServiceâ tutorial to create a Web Service on your system.
Additionally, in able to develop an Android application you must first of all set-up the Android
development environment. Kindly study âAndroid_Startupâ tutorial to set-up an Android system.
Objective: Create âNativeâ Android client to present data from a Web Service.
Figure 1-1: WS data displayed by web browser.
Android WS client: Type WS address â Start new screen â Pull data & present
Figure 1-2: Android Web Service client.
4. 4
2Technical Implementation
2.1 CreateAndroid WebService Client
Make sure the Android developing interface (JAVA-ADT) is set-up on your computer, If not go
through the âAndroid_Startupâ tutorial.
Create a new Android application project and give a name (WebService) to the project .
ï File â New â Android Application Project â give name to the project and basically just click
on NEXT until finish.
INFO: More details on how to create a new project is described in âAndroid_Startupâ.
The Android development environment should be as shown in Figure 2-1. We will modify this
application (Hello world!) into a Web Service client.
Figure 2-1: Development environment with project (WebService).
We would like to create additional xml and java files as seen in Figure 2-2.
ï· Package Explorer â WebService â src â SensorValue.java
5. 5 Technical Implementation
Web Service Client
ï· Package Explorer â WebService â layout â activity_sensort_value.xml
Figure 2-2: Additional needed files.
ï· To create additional java files.
ï File â New â Class
ï Name: XXX (in this case Name: SensorValue)
NOTE!! The SensorValue.java file should be under âsrcâ folder as shown in Figure 2-2.
ï· To create additional xml files.
ï ClicK: icon (Left top corner) â Android â Android XML File â Next
ï Resource Type: Layout â File: activity_sensor_value.xml â Root Element:
TableLayout â Finish. (See details in Figure 2-3)
INFO: an activity_sensor_value.xml file should appear under layout.
6. 6 Technical Implementation
Web Service Client
Figure 2-3: Creating "activity_sensor_value.xml" file
2.2 Android Programming
Now we would like to modify and fill in xml and java files with codes. We will first of all focus on to
filling android codes to the correct files. Once we finish with this process then we will execute and
run the application on an Android Virtual Device and also on a real Android device. Comments on all
the codes and programming structures are listed at the end of this tutorial.
The following files will be modified or/and filled in with codes: MainActivity.java, SensorValue.java,
activity_sensor_value.xml, strings.xml, AndroidManifest.xml, main.xml.
Note!! main.xml in your case is activity_main.xml
Fill in files with codes
We will start to fill in codes in strings.xml.
ï Double click: strings.xml â Fill in codes in the strings.xml file
10. 10 Technical Implementation
Web Service Client
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class SensorValue extends Activity implements OnClickListener
{
private Handler h = new Handler();
private Runnable myRunnable = new Runnable()
{
public void run()
{
//do stuff
new LongRunningGetIO().execute();
//run again in one second
h.postDelayed(myRunnable, 1000);
}
};
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensor_value);
findViewById(R.id.start_button).setOnClickListener(this);
}
@Override
public void onClick(View arg0)
{
Button b = (Button)findViewById(R.id.start_button);
b.setClickable(false);
new LongRunningGetIO().execute();
h.postDelayed(myRunnable, 1000);
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String>
{
11. 11 Technical Implementation
Web Service Client
protected String getASCIIContentFromEntity(HttpEntity entity) throws
IllegalStateException, IOException
{
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
@Override
protected String doInBackground(Void... params)
{
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://"+ message);
String webServiceXML = null;
try
{
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
webServiceXML = getASCIIContentFromEntity(entity);
}
catch (Exception e)
{
return e.getLocalizedMessage();
}
return webServiceXML;
}
protected void onPostExecute(String webServiceXML)
{
String nameData="";
String valueData="";
if (webServiceXML!=null)
{
// parse
try {
DocumentBuilderFactory dbFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder =
dbFactory.newDocumentBuilder();
InputSource s = new InputSource(new
StringReader(webServiceXML));
12. 12 Technical Implementation
Web Service Client
Document doc = dBuilder.parse(s);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Terminal");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
nameData =
eElement.getElementsByTagName("Name").item(0).getTextContent();
valueData =
eElement.getElementsByTagName("Value").item(0).getTextContent();
}
}
} catch (Exception e) {
e.printStackTrace();
}
TextView name = (TextView) findViewById(R.id.nameTextview);
name.setTextColor(Color.parseColor("#0147FA"));
name.setText(nameData);
TextView value = (TextView) findViewById(R.id.valueTextview);
value.setTextColor(Color.parseColor("#0147FA"));
value.setText(valueData + " " +(char) 0x00B0 + "C");
}
Button button = (Button)findViewById(R.id.start_button);
button.setClickable(true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sensor_value, menu);
return true;
}
}
MainActivity.java codes:
package no.hit.webservice;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
13. 13 Technical Implementation
Web Service Client
import android.widget.EditText;
public class MainActivity extends Activity
{
public final static String EXTRA_MESSAGE = "no.hit.webservice.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
/** Called when the user clicks the Send button */
public void sendMessage(View view)
{
Intent intent = new Intent(this, SensorValue.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
AndroidManifest.xml codes:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="no.hit.webservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="no.hit.webservice.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="no.hit.webservice.SensorValue"
android:label="@string/title_activity_sensor_value"
android:parentActivityName="no.hit.webservice.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
14. 14 Technical Implementation
Web Service Client
android:value="no.hit.webservice.MainActivity" />
</activity>
</application>
</manifest>
2.3 Execute and Run the App
We are now finishing with Android programming phase (All the files are loaded with codes). Next we
will execute and run the Android WebService client.
Run on Android Virtual Device (AVD)
ï· Simulate an application in a Virtual Device
ï File â Save to save all the changes
ï Click: âWebServiceâ â Project â CleanâŠ
ï Click: âWebServiceâ â Run â Run as â 1 Android Application
Recommend: Repeat all the three steps above every time you run your app.
NOTE!! Important to click on âWebServiceâ.
Wait approximately a few minutes for your computer to load the Virtual Device (AVD). In case a
window is pop-up as seen in Figure 2-5, just click Yes â OK to continue.
INFO: unlike other programming languages, to compile and run codes on Android is a very slow
process, due to the reason the required time to launch AVD. Once AVD appears â unlock â Wait.
Figure 2-5: Enable logcat service.
Your new created âWebServiceâ is running on Android Virtual Device by the given name MyDevice.
ï Enter: address of the WebService â Get â Start
Data extracted from the Web Service should display on AVD.
15. 15 Technical Implementation
Web Service Client
Figure 2-6: Android "WebService" application.
Run on a real Android Device
All the written codes are compressed in a âapkâ file, in this case the file name is WebService.apk. This
specific file has to be downloaded (transferred) and installed on the real device. The file can be
passed to the android device throug Bluetooth technology or simply by using a cable.
Location of apk file: workspace â WebService â bin folder â WebService.apk
INFO: In my case the whole path to the WebService.apk is located in C:/User/levo/workspace/
WebService /bin/ WebService.apk
Note!! Levo is my user name, so it is different name in your computer.
2.4 Comments & Explainations
This section will focus on functionalities of different files (java and xml) and comments on all the
codes containing in these files. Furthermore, src, values and layout folders are folders that
developers mostly interact with, will also be given discussions.
Layout XML code
all the codes written in the xml files within layout folder specifies the layout of the screen. In this
case we have two different xml files, activity_sensor_value.xml and activity_main.xml, these are
located in the layout folder. Since the Web Service client (application) consists of two different
screens and each separate screen needs their own xml file to control the layout.
Activity_main. xml or main.xml controls the layout of the first screen. Here we refer the first screen
as the first page appears on the device when the application starts up. In these case we enter the
address of the Web Service on the first screen.
activity_sensor_value.xml controls the layout of the second screen. In this case we display data
published from the Web Service on the second screen.
16. 16 Technical Implementation
Web Service Client
Figure 2-7: App consists of two screens.
Java source code
The Java code is what drives everything, where the main duty is to deliver the job given based on
input from the screen, in other words commands given by the user. Java code executes and runs the
application.
MainActivity.java and SensorValue.java are the two files that contain Java codes. Each java files
controls, executes and delivers the job based on the command given as input from layout screen.
Java code can be considered as unseen engine spinning behind the current screen, always listening
for a command from the user, where its mission is to deliver the job once a command is detected.
MainActivity.java file deliver the job based on input from the first screen, while SensorValue.java file
also has the same function but listens to the input from the second screen instead.
The Java file operation in our case can be simplified as below:
First screen â Get (Input ,Command) â MainActivity.java â Result (copy the WS address, send to
the second activity (SensorValue.java) and open the second screen.
Second screen â Start (Input ,Command) â SensorValue.java â Result (get the WS address from the
first activity, get and update data from WS every second, display data on second screen). The whole
process is illustrated in Figure 2-8.
17. 17 Technical Implementation
Web Service Client
Figure 2-8: Chart flow of WebService app.
Values folder
This folder contains xml files as resources (dimensions, strings, styles), from which other files can pull
data resources to fulfill various functions. All the text strings are stored in the strings.xml as text
resource from which other files, methods, activity are able to utilize. A word string is stored in an xml
file as seen below.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello_world">Hello world!</string>
</resources>
AndroidManifest.xml
The manifest file glues everything together, this specific file describes what the application consists
of, what all its main building blocks are, what permissions it requires and etc. A Manifest file fills
automatically codes by it selves while we are developing the app. The code of line below has to be
written by the developer him selves to allow the application to access to the internet.
<uses-permission android:name=âandroid.permission.INTERNETâ/>
Activity_main.xml or main.xml
Since this file is located in the layout folder so the codes containing in the main.xml file are mostly
EditText, TextView and buttons of various type. The codes in this file control where on the screen
these features should be placed and their characteristics.
Main.xml file controls the layout of the first screen in the created WS client, from which there are
two features; EditText and a âGetâ button.
EditText: is needed for users to be able to type input to the system, here the input is referred to a
WebService address.
18. 18 Technical Implementation
Web Service Client
âGetâ button: when user press this button, a command is detected by codes written in a java and
process until the result is delivered.
Layout of first screen
We set the screen as TableLayout type, we split the table up to two rows of which the first row
(Android define first row as row 0) is reserved for TextEdit while the second row (row 1) is occupied
by the âGetâ button. Additionally the table is split in to three columns where one of the columns is
reserved by âGetâ button. A thickness of â5dpâ is surrounding along the whole table to the outer
edge. The rest of the codes in the activity_main.xml are logical and easy to understand.
Figure 2-9: Layout design of first screen.
Layout of second screen
We set the second screen also as TableLayout type, we split the table up to three rows of which the
first row (Android define first row as row 0) is reserved for a âStartâ button while the second and
third rows (row 1 and row 2) are occupied by two TextViews with different properties. Additionally, a
thickness of â5dpâ is surrounding along the whole table to the outer edge. The rest of the codes in
the activity_main.xml are logical and easy to understand. Hence, âTemperatureâ and â26,7 °Câ are
dynamic TextViews, meaning they are displayed corresponding to changes in data broad casted from
the WebService.
19. 19 Technical Implementation
Web Service Client
Figure 2-10: Layout design of second screen.
Java files
The actual hardcore programming taken place in the java files, the java code is what drives
everything. This Web Service client application consists of two java files; MainActivity.java reacts to
the input from the first screen (main.xml) while SensorValue.java deliver the work based on the
command from the second screen (activity_sensor_value.xml).
MainActivity.java
The method âsendMessageâ will reacts based on the users interaction to the âGetâ button in
main_xml file. Once the button is pressed the method will start to process and the final result to the
work is totally depending on what code is specified for this method. In this case the missions of the
âsendMessageâ method are;
ï· First of all create a new intent object by the name âintentâ. Intent is a service in Android
which mostly used to start a new activity. Since we are currently in MainActivity.java, intent
will start SensorValue.java as new activity.
ï· Define the EditText (id: edit_message) as editText in this java file
ï· copy the entered address in the EditText to the âmessageâ. Example, if you have typed in
<<128.39.35.239:8080/WebService/Temp_value>> the âmessageâ contains the whole string
that was just typed in.
message = 128.39.35.239:8080/WebService/Temp_value
ï· When intent is activated and start another activity, the content of the message will also be
sent to the new started activity, which in our case is SensorValue.java.
public void sendMessage(View view)
{
20. 20 Technical Implementation
Web Service Client
Intent intent = new Intent(this, SensorValue.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
SensorValue.java
âmyRunnableâ method will put the system into sleep for a certain time period, in this case it is set
one second. We use this method to get data from the WebService once in a second.
private Runnable myRunnable = new Runnable()
{
public void run()
{
new LongRunningGetIO().execute();
//run again in one second
h.postDelayed(myRunnable, 1000);
}
};
âonClickâ method calls for other method to perform a certain task.
public void onClick(View arg0)
{
Button b = (Button)findViewById(R.id.start_button);
b.setClickable(false);
new LongRunningGetIO().execute();
h.postDelayed(myRunnable, 1000);
}
This part of code runs in the background of the system, its tasks are to; get the message (Entered in
the EditText) passed over from the first activity then start internet connection with the WebService,
where the address is contained in the âmessageâ.
protected String doInBackground(Void... params)
{
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
21. 21 Technical Implementation
Web Service Client
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://"+ message);
String webServiceXML = null;
try
{
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
webServiceXML = getASCIIContentFromEntity(entity);
}
catch (Exception e)
{
return e.getLocalizedMessage();
}
return webServiceXML;
}
With this code we only extract (parse data from WS to Android) the data of interest from the
WebService (Temperature and 26,7 °C) then we give properties to these data. All the mentioned
actions will be activated once the âStart_buttonâ is pressed.
protected void onPostExecute(String webServiceXML)
{
String nameData="";
String valueData="";
if (webServiceXML!=null)
{
// parse
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder=dbFactory.newDocumentBuilder();
InputSource s = new InputSource(new StringReader(webServiceXML));
Document doc = dBuilder.parse(s);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Terminal");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
nameData = eElement.getElementsByTagName("Name").item(0).getTextContent();
valueData = eElement.getElementsByTagName("Value").item(0).getTextContent();
}
}
22. 22 Technical Implementation
Web Service Client
} catch (Exception e) {
e.printStackTrace();
}
// Temperature TextView properties
TextView name = (TextView) findViewById(R.id.nameTextview);
name.setTextColor(Color.parseColor("#0147FA"));
name.setText(nameData);
// Temperature value TextView properties
TextView value = (TextView) findViewById(R.id.valueTextview);
value.setTextColor(Color.parseColor("#0147FA"));
value.setText(valueData + " " +(char) 0x00B0 + "C");
}
Button button = (Button)findViewById(R.id.start_button);
button.setClickable(true);
}
}
Note!! When programming in java files we need to import many different libraries to support the
code. In Android we do not need to put much focused on this problem. While you are programming
every now and then just click: âCtrl + Shift + Oâ Android will import all necessary libraries to support
the written codes. As the second options is to right click texts with underlines, then choose import.
At this moment you should be able to execute and run the Web Service client on an emulator (AVD)
and also on the real physical Android device. But most important of it all is that you understand the
programming structure in Android and have an idea over the functional of the codes in different xml
and java files.
23. HĂžgskolen i Telemark
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Faculty of Technology, Postboks 203, KjĂžlnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01
Telemark University College
Faculty of Technology
KjĂžlnes Ring 56
N-3918 Porsgrunn, Norway
www.hit.no