Read text file from internet in android

When you create an Android application that reads content of a text file from internet to display in a TextView, this tip might be useful to you. To read a text file from an input URL, first you need to create an instance of URL class to point to the specified file location. Then you will use the HttpURLConnection class to make a request to the server. You can get an instance of the HttpURLConnection by calling the openConnection method of the URL instance. The HttpURLConnection instance has a method called getInputStream. This method returns an InputStream object. To get content of the file from InpuStream object, you can use the BufferedReader class. BufferedReader reader allows you to read the file one by one character, multiple characters (an array of char), or line by line. When you create an instance of BufferedReader to read the file, you will pass to its constructor an instance of the InputStreamReader that wraps the InputStream object.

Now to have a workable example application, you will create new Android application. Then modify the activity_main.xml file to add one TextView as below. This TextView is used to display content of the file read from the internet.

<LinearLayout 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:orientation="vertical"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >

   <TextView
     android:id="@+id/text_view"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:textSize="20sp" />

</LinearLayout>

Here is the content of the MainActivity file to read a text file from internet and display the content of the file in the TextView. When the application starts, the onStart method is invoked. In the onStart method, an instance of BackTask class is created and its execute method is called to start reading data from the specified URL. Reading data from internet may take much time so it is a good idea to place this process in a background. One way to place a process in background is by using the AsynckTask class. The AsynckTask class allows you to handle things before process starts, during process in progress, and after the process finished. In this example, I display a progress dialog before the reading process begins in the onPreExecute method. The reading task is performed in the doInBackground method. In the OnPostExecute method, I close the progress dialog and display the content of the file in the TextView.

package com.example.andtip;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.view.View;
public class MainActivity extends Activity {
Activity context;
TextView txtview;
ProgressDialog pd;
   protected void onCreate(Bundle savedInstanceState) {
   //TODO Auto-generated method stub
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   context=this;
  

}

  
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
       getMenuInflater().inflate(R.menu.main, menu);
       return true;
   }
  
  
   public void onStart(){
   super.onStart();
  
   BackTask bt=new BackTask();
   bt.execute("http://www.worldbestlearningcenter.com/example.txt");
  
  
   }
  
  //background process to download the file from internet
   private class BackTask extends AsyncTask<String,Integer,Void>{
   String text="";
   protected void onPreExecute(){
     super.onPreExecute();
     //display progress dialog
     pd = new ProgressDialog(context);
     pd.setTitle("Reading the text file");
     pd.setMessage("Please wait.");
     pd.setCancelable(true);
     pd.setIndeterminate(false);
     pd.show();
    
     }
  
  
  
     protected Void doInBackground(String...params){
     URL url;
        try {
        //create url object to point to the file location on internet
       url = new URL(params[0]);
       //make a request to server
       HttpURLConnection con=(HttpURLConnection)url.openConnection();
       //get InputStream instance
       InputStream is=con.getInputStream();
       //create BufferedReader object
       BufferedReader br=new BufferedReader(new InputStreamReader(is));
       String line;
       //read content of the file line by line
       while((line=br.readLine())!=null){
        text+=line;
       
        }
       
        br.close();
       
       }catch (Exception e) {
       e.printStackTrace();
       //close dialog if error occurs
       if(pd!=null) pd.dismiss();
       }
    
        return null;
    
     }  
    
    
     protected void onPostExecute(Void result){
     //close dialog
     if(pd!=null)
     pd.dismiss();    
     txtview=(TextView)findViewById(R.id.text_view);
     //display read text in TextVeiw
     txtview.setText(text);
    
     }    
    
    
     }
  
}

Android read file from internet

Posted by: Dara | post date: 06-22-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.