Android Read Text File from Remote Server

Reading text file from server in one thing that you will not always use why working on android projects. May be for once you may found yourself thinking about how to read text file from remote server, then this android tip will be of help to you.

Just like many things in programming, there are different ways you can use to achieve the same result but here I am going the use the old Android AsyncTask with URL class.

I have also written some related tutorials that you might find interested. The link is shared below.

1. Read a file from raw folder in android 

2. Load html file from assets folder in android 

3. Read CVS file from remote server in android

4. Upload image to remote server in android 

First, to test our code when we finish, we need to create a text file and upload it to our server. You can name your text file a name of your choice.

Get the path to the text file in your server because you are going to use it in the application.

The screen-shot below shows the results of reading a text file from remote server in android.

android text file download

The application contain a Button and TextView widgets. When the button is clicked, the application will make a network call and display the content of the remote text file on the TextView.

1. Create a new android app

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidRemoteTextFile

Package: com.inducesmile.androidremotetextfile

Select Empty Activity

Name your activity: MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

2. Add the code below to activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    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="com.inducesmile.androidremotetextfile.MainActivity">
    <Button
        android:id="@+id/load_file_from_server"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/read_text_file_from_server"
        android:background="@color/colorAccent"/>
    <TextView
        android:id="@+id/content_from_server"
        android:layout_width="wrap_content"
        android:textColor="@color/colorBlack"
        android:textSize="14sp"
        android:layout_marginTop="24dp"
        android:layout_height="wrap_content" />
</LinearLayout>

3. Update AndroidManifest.xml

Since the application is going to make a network call, we will add user permission for Internet. Open your project AndroidManifest.xml file and add the code below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.inducesmile.androidremotetextfile">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

 4. Update MainActivity.java

Open the MainActivity class, we are going to get the instances of the Button and TextView widgets.

Attach an event listener to the button object. Create an inner class that inherits from the default android AsyncTask class.

We are using the AsyncTask class in other to perform the network call operation in a background thread.

The complete code for this class is as shown.

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private TextView fileContent;
    private static final String PATH_TO_SERVER = "path_to_text.txt";
    private Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fileContent = (TextView)findViewById(R.id.content_from_server);
        Button loadTextButton = (Button)findViewById(R.id.load_file_from_server);
        loadTextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DownloadFilesTask downloadFilesTask = new DownloadFilesTask();
                downloadFilesTask.execute();
            }
        });
    }
    private class DownloadFilesTask extends AsyncTask<URL, Void, String> {
        protected String doInBackground(URL... urls) {
           return downloadRemoteTextFileContent();
        }
        protected void onPostExecute(String result) {
            if(!TextUtils.isEmpty(result)){
                fileContent.setText(result);
            }
        }
    }
    private String downloadRemoteTextFileContent(){
        URL mUrl = null;
        String content = "";
        try {
            mUrl = new URL(PATH_TO_SERVER);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            assert mUrl != null;
            URLConnection connection = mUrl.openConnection();
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            while((line = br.readLine()) != null){
                content += line;
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
}

 5. Run and test your application

If you are done without any error, you can run your application and click on the button to see the content of your remote text file.

Please note that you need to add the path where your text file leaves in your server.

6. Some errors you might see

If you try to call the downloadRemoteTextFileContent() method in the onCreate() method without using the AsyncTask class, you will definitely experience any of these errors.

1. Only the original thread that created a view hierarchy can touch its views.

2. android.os.NetworkOnMainThreadException

These errors occurred when you try to make network call in the UI thread.

Finally, if you have used another method to achieve this, I will appreciate it if you can share your solution with us.

 

Add a Comment