Tutorial

Android App Example - Http data communication with a web server


Develop a simple android app that talks to your server. Data can be transported over the HTTP Protocol, hence any web server can interact with your android app. Test with a sample Ruby on Rails and PHP server.


Introduction


Getting your android app to interact with a server over a network is a very important feature. It can extend countless poosibilities to your app. This tutorial demonstrates how to add this capability to an Android app. We will also create a Ruby on Rails web server which will interact with our Android Client over a local network. So make sure you have the following tools installed on your system:

  • Eclipse with Android SDK
  • Android Virtual Device or a physical Android phone to test our app
  • Ruby on Rails / PHP for a server
  • Network Connection

Step 1: Create a new Android App in Eclipse.


  • Open Eclipse and go to File >> New >> Project >> Android >> Android Application Project
  • Give the project any name e.g. “AndroidHttpClient” and click Next.
  • Check “Create Activity” and select “Blank Activity”. Click Next.
  • You are asked to enter information about the new “Blank Activity”. Let them be their default values. Click Finish to create the new project.


Step 2: Design of layout of your app


Open the file /res/layout/mail.xml. It contains the xml code of the user interface of our app. In our case, this code corresponds to the main activity we created in the previous step. Whenever the app will be launched, this activity will be shown. Now change the view mode from Graphical Layout to text editing mode if not already changed and replace that code with the following:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

<EditText

android:id="@+id/senddata_txt"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:ems="10" />

<Button

android:id="@+id/send_btn"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Send Data"

android:onClick="on_send_click" />

<TextView

android:id="@+id/show_text"

android:layout_width="match_parent"

android:layout_height="276dp" />

</LinearLayout>

This will add one button, one TextEdit widget and one TextView widget to the interface, each with a unique id. Note that the Send Data button has an onClick binder attached to the function "on_send_click".


Step 3: Add Network Access permissions to the Android manifest file


This is a very important step and is many times the cause of errors if it is skipped. Open the file /AndroidManifest.xml. Add the following lines above the "Application" tag.

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Adding these lines to the Manifest file will give this app the permissions to communicate over the network, which is the goal of our app.


Step 4: Create a Background Task which calls the network methods.


In Android, there is a UI Thread which renders all the UI elements to the display and handles all the user interaction. This thread is also the main thread of the app. For a more responsive user experience, it is better if we put all the time consuming tasks to a separate thread. Android has a very simple class to create to new thread to perform tasks. It is called AsyncTask, meaning Asynchronous task.

Making a network request can be a time taking process. The default android environment forbids network calls to be called from the UI thread. If any such call is made, a NetworkOnMainThreadException is raised, terminating the application. Hence, we put the network calls in a background thread by creating a new class inheriting from the class, AsyncTask.

private class HttpSend extends AsyncTask<String, Void, String>

{

@Override

protected String doInBackground(String... str) {

try

{

String get_url = "http://10.109.9.42:3001/recieve?q=" + str[0].replace(" ", "%20");

HttpClient Client = new DefaultHttpClient();

HttpGet httpget;

ResponseHandler<String> responseHandler = new BasicResponseHandler();

httpget = new HttpGet(get_url);

String content = Client.execute(httpget, responseHandler);

return content;

}

catch(Exception e)

{

System.out.println(e);

}

return "Cannot Connect";

}

protected void onPostExecute(String result) {

TextView tv = (TextView) findViewById(R.id.show_text);

tv.setText(result);

}

}

OK. This might be too much to take at once. But I will try to explain the salient features of this class.

  • The HttpSend is a new class inhering from AsyncTask template class.
  • The doInBackground method is automatically executed in a new thread when a class object’s execute method is called.
  • The Client.execute method performs the network request and return a string containing the response data.
  • onPostExecute method is called automatically after the doInBackground method which displays the response in the TextView.

P.S. - Change the IP address and port number in the get_url String to your server’s IP address and port.


Step 5: Define the onClick binder method for Send Data button


We have created a class to create the network request. However, we need to call the methods of this class only when the user clicks Send Data button. Before sending data, the user enters text to be sent in the TextEdit widget. We would also need to retrieve that text before executing our network call. Insert the following method after the onCreate method in the MainActivity class :

public void on_send_click(View v)

{

EditText send_txt = (EditText) findViewById(R.id.senddata_txt);

HttpSend httas = new HttpSend();

httas.execute(send_txt.getText().toString());

}

As you can observe, we create a new instance of HttpSend class, then call it’s execute method, pass the EditText’s text as the string argument. This will call the methods inside the HttpSend class, which will perform the network request.

Now our android application is complete and you can run the code in a Android Virtual Device or a physical device. However, the app won’t work because we still need to create a server to which our app can connect.


Step 6: Create a Ruby on Rails/PHP server on your machine


Ruby on Rails :

Execute the following commands in Terminal to create the Ruby on Rails application :

rails new appserver

rails g controller Home getdata

Go to the rails project directory and open the file app/controllers/home_controller.rb

In the file, modify the getdata method as follows:

def open

render :text => "Server Recieved: #{params[:q]}"

return

end

Finally execute the server by running the following command in the rails app directory:

rails server

PHP

If you have a php server installed, create a new file named appserver.php in your webroot directory and insert the following code:

<?php

$q = $_GET['q']; echo "Server Recieved: ".$q; ?>


Step 7: Test your Android App with the server


Now our client and server, both are created. So run your Android app and the server on your machine. Make sure you have entered the correct IP address of your machine in the Android app. In the app, enter any data in the text field and click "Send Data”. You should see that data below the button.

Rohan Raja

Recently graduated, majoring in Mathematics and Computing from IIT Kharagpur, Rohan is a technology enthusiast and passionate programmer. Likes to apply Mathematics and Artificial Intelligence to devise creative solutions to common problems.