Monday, June 18, 2012

How To Get Text From Web And Display In Text View Android



This is a sample activity which shows How to get text files from the web and display them using the TextView view.
Underlying Algorithm:
Basic description of algorithm in step by step form:
1.) Create a Project httpsData.
2.) Add the relevant permissions to your AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.apps.httpsData"
     android:versionCode="1"
     android:versionName="1.0.0">

    <uses-permission android:name="android.permission.INTERNET" />
    <application android:icon="@drawable/icon" 
       android:label="@string/app_name">
        <activity android:name=".httpsData"
                 android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
3.) Define a helper function called OpenHttpConnection() in your activity that opens a connection to a HTTP server and returns an InputStream object.
private InputStream OpenHttpConnection(String urlString) throws IOException
{
    InputStream in = null;
    int response = -1;
             
    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
               
    if (!(conn instanceof HttpURLConnection))                  
        throw new IOException("Not an HTTP connection");
     
    try{
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        response = httpConn.getResponseCode();              
        if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                              
        }                  
    }
    catch (Exception ex)
    {
        throw new IOException("Error connecting");          
    }
    return in;  
}
4.) Run the application.
Steps to Create:
1.) Open Eclipse. Use the New Project Wizard and select Android Project. Give the respective project name i.e. httpsData. Enter following information:
Project name: httpsData
Build Target: Android 2.3
Application name: httpsData
Package name: com.apps.httpsData
Create Activity: httpsData
On Clicking Finish httpsData code structure is generated with the necessary Android Packages being imported along with httpsData.java. httpsData class will look like following:
package com.apps.httpsData;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class httpsData extends Activity {
    /** Called when the activity is first created. */
        ImageView img;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String str = DownloadText("http://www.edumobile.org/android/");
        TextView txt = (TextView) findViewById(R.id.text);
        txt.setText(str);      
    } 
 
    private String DownloadText(String URL)
    {
        int BUFFER_SIZE = 2000;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "";
        }
     
        InputStreamReader isr = new InputStreamReader(in);
        int charRead;
        String str = "";
        char[] inputBuffer = new char[BUFFER_SIZE];        
        try {
            while ((charRead = isr.read(inputBuffer))>0)
            {                  
                //—convert the chars to a String—
                String readString = String.copyValueOf(inputBuffer, 0, charRead);
                str += readString;
                inputBuffer = new char[BUFFER_SIZE];
            }
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }  
        return str;      
    }

    private InputStream OpenHttpConnection(String urlString)
    throws IOException
    {
        InputStream in = null;
        int response = -1;
             
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
               
        if (!(conn instanceof HttpURLConnection))                  
            throw new IOException("Not an HTTP connection");
     
        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();              
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                              
            }                  
        }
        catch (Exception ex)
        {
            throw new IOException("Error connecting");          
        }
        return in;  
    }
}
Output –The final output:

No comments:

Post a Comment