Print Shortlink

Dive into Android development – V

Let’s try to connect to a server resource from an Android application and display the data. I have created a very simple JSP page ‘server.jsp’ that returns the server date and time. This date and time will be displayed in our Android application in a simple TextView component.
The server.jsp has the following code
                <%@page import=“java.util.Date”%>
                <%= new Date()%>

In the onCreate method of the Activity, you will use the normal Java approach to connect to a server and fetch data, i.e, using the java.net and java.io package. The code for connecting to the server.jsp is given below.
        TextView dateText = (TextView)findViewById(R.id.dataText);
        String address = http://YourAddress/server.jsp;
        try {
                     URL url = new URL(address);
                     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                     if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                         InputStream inputStream = urlConnection.getInputStream();
                         BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
                         String line = null;
                         while ((line = br.readLine()) != null) {
                               dateText.setText(line);
                         }
                        br.close();
                       }
           } catch (Exception e) {
                    Log.e(“Error fetching data “, e.getMessage());
            }

When you run this code, you will get an error logged into to your LogCat as shown below.
You have to add a permission attribute in the Android Manifest file for your application to be able to connect to the internet. Add the following line in AndroidManifest.xml file. 
               <uses-permission android:name=“android.permission.INTERNET”/>

You can play with the manifest file using the design wizard instead of manually editing it.
So all set and done, your app connects to the server resource, loads the data from the server and displays it in the TextView component.

Leave a Reply


six + = 13