Network Access in Android Applications

This entry is part 29 of 50 in the series Android Development Primer

In all the earlier posts throughout this tutorial section, we’ve been dealing with standalone applications i.e. ones that require no network access. But with the ever growing Android market and competitive applications on the play store, there will be times when you will want to introduce some type of network functionality in your application.

In this post, I’m going to help you create an application that will have a very basic network access. We’ll be providing the application a website and we’ll be displaying the source code of that webpage. Of course, we’ll need internet access on the device we run this application on. As far as emulators are concerned, they derive their network access from your system’s internet connection. So fire up an activity and start coding. Complete Source Code is at the bottom.

  • The first thing we need to do is add a permission in the manifest file for internet access. It tells the Android system that the application requires an active internet connection and it will access the connection as and when required.
  • So open up the Manifest file and switch to the permissions tab. Add in the Android.permission.INTERNET permission from the drop down menu.
  • Next we need to setup the layout. We’re going to have a minimal layout consisting of an EditText, a TextView and a Button. We’ll be entering the website name in the EditText and the TextView will display the source when the button is clicked. We’ll span the TextView over the entire area left after placing the other elements.
  • Switch over to the MainActivity.java file and declare the elements appropriately. Remember to make them final variables.
  • We’ll now set up the onClickListener() method of the button. Inside the onClick() method, write the following lines.
    try{
    			URL url = null;
    			url = new URL(et.getText().toString());
    			URLConnection conn = url.openConnection();
    			BufferedReader x= new BufferedReader(new InputStreamReader(conn.getInputStream()));
    			String line = "";
    			while((line=x.readLine())!=null){
    				tv.append(line);
    			}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    
  • Save the activity and launch it in an emulator or a device. Here’s what it looks like on my Gingerbread emulator.

networkinit network

Understanding the Code

  • A closer look at the code clearly shows that we are not using any new concepts but basic Java.
  • We create an object of the URL class of Java and pass it the string value from the EditText.
  • We then set up a URL Connection. The openConnection() method helps us in doing so.
  • We are also using the basic BufferedReader class that we use in basic java programs. This is to read the source code of the website and accept it as input.
  • The whole section has been enclosed in a try catch block because we are dealing with networking here and there are many things that can go wrong like link failure, unrecognized connection etc. We do not want our application to crash but to properly handle these exceptions.
  • Also remember that we are doing exactly what a web browser does while rendering a webpage. Then the question arises why are we only seeing the source code instead of the webpage as in a web browser. This is because web browsers are programmed to understand and render hypertext while out simple TextView is not. Thus we are only able to see the raw source code.

COMPLETE SOURCE CODE

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ems="10" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:text="Get Source" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/button1"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText1" />

</RelativeLayout>

MainActivity.java

package com.nero.myfirstapp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText et = (EditText) findViewById(R.id.editText1);
        final Button b = (Button) findViewById(R.id.button1);
        final TextView tv = (TextView) findViewById(R.id.textView1);

        b.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try{
					URL url = null;
					url = new URL(et.getText().toString());
					URLConnection conn = url.openConnection();
					BufferedReader x= new BufferedReader(new InputStreamReader(conn.getInputStream()));
					String line = "";
					while((line=x.readLine())!=null){
						tv.append(line);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
    }

}

Series Navigation<< Introducing Android Debug Bridge – Part IIContent Providers in Android >>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy This Password *

* Type Or Paste Password Here *

43,702 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>