Android – How to read CSV file from Remote Server or Assets Folder in Android

In this android tips, we are going to learn how to read CSV file from remote server or from assets folder in android.

If you are new to this type of file extension, CSV file means comma-separated values (CSV). It is a normal plain-text file that stores data in column by column, and split it by a separator.

Some example of file that you can get is MS excel if you have used it before.

You can read csv file in android the way you can actually read an ordinary text file. The only difference now is when you want to manipulate the csv file in columns then you need to do more by separating each row of string in columns.

Check for example, if you are give a csv file in android and you are asked to use some particular columns to plot a graph or present the values of the csv file in a tabular format.

Before we go deep into parsing csv file in android, I will like to share how your can read a text file from remote server in android. This tutorial share similar code with the above android tips and it will important you first read the tutorial above.

I have also written some android tips on how to use the content of the csv file to achieve the following in android application.

1. Read cvs file and use its content to plot a graph in android.

2. Read cvs file and present its content in tabular form.

First, we need to create a .cvs file and upload it to your server. If you don’t know how to do that I have created one already for you which I used in this project. You can download it here.

See the screen-shot of what we are planning to do below.

Android csv parser

1. Create a new android app.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidReadCVSFile

Package: com.inducesmile.androidreadcvsfile

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.

Open the default activity_main.xml file Android Studio created for us. Add a Button and TextView widgets on the layout file.

When the button is clicked it will read the content of the .csv file and display it on the TextView.

Add the code below to the 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.androidreadcvsfile.MainActivity">
    <Button
        android:id="@+id/load_file_from_server"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/read_cvs_file_from_remote_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

It is important to understand that reading a file from a remote server or location over the internet has slight different approach with reading from from with the application.

For remote reading of .csv file or any kind of file, it has to be done in a background thread since android gets angry if you implement network calls in the main UI thread.

For the remote reading of the .csv in android, we will use the old AsyncTask class.

Read .CVS file from remote server in android example

Open the MainActivity.java file and add the code below.

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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;
import java.util.ArrayList;
import java.util.List;
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 .csv file";

    @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, List<String[]>> {
        protected List<String[]> doInBackground(URL... urls) {
            return downloadRemoteTextFileContent();
        }
        protected void onPostExecute(List<String[]> result) {
            if(result != null){
                printCVSContent(result);
            }
        }
    }
    private void printCVSContent(List<String[]> result){
        String cvsColumn = "";
        for (int i = 0; i < result.size(); i++){
            String [] rows = result.get(i);
            cvsColumn += rows[0] + " " + rows[1] + " " + rows[2] + "\n";
        }
        fileContent.setText(cvsColumn);
    }
    private List<String[]> downloadRemoteTextFileContent(){
        URL mUrl = null;
        List<String[]> csvLine = new ArrayList<>();
        String[] content = null;
        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.split(",");
                csvLine.add(content);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return csvLine;
    }
}

Read .CVS file from Assets folder in android

In this case, we do not need to implement a background thread if the file size is small. If you .csv size is too big, you can consider doing it in a background thread or a service and update the UI views.

Change the content of MainActivity.java class with the code below.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class CVSActivity extends AppCompatActivity {
    private static final String TAG = CVSActivity.class.getSimpleName();
    
    private TextView fileContent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cvs);
        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) {
                List<String[]> csvContent = readCVSFromAssetFolder();
                printCVSContent(csvContent);
            }
        });
    }
    private List<String[]> readCVSFromAssetFolder(){
        List<String[]> csvLine = new ArrayList<>();
        String[] content = null;
        try {
            InputStream inputStream = getAssets().open("local.cvs");
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while((line = br.readLine()) != null){
                content = line.split(",");
                csvLine.add(content);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return csvLine;
    }
    private void printCVSContent(List<String[]> result){
        String cvsColumn = "";
        for (int i = 0; i < result.size(); i++){
            String [] rows = result.get(i);
            cvsColumn += rows[0] + " " + rows[1] + " " + rows[2] + "\n";
        }
        fileContent.setText(cvsColumn);
    }
}

 5. Using third Party Library to Parse .CSV file in android

Finally, we are going to look at how we can parse .csv file in android using opencsv library. If you are thinking what might be the advantage of using this library, I have listed it below. This is base on the author of the library. You can read more about the opencsv library in their offical website

opencsv supports all the basic csv-type things you’re likely to want to do:

* Arbitrary numbers of values per line.

* Ignoring commas in quoted elements.

* Handling quoted entries with embedded carriage returns (ie entries that span multiple lines).

* Configurable separator and quote characters (or use sensible defaults).

* Read all the entries at once, or use an Iterator style model

* Creating csv files from String[] (ie. automatic escaping of embedded quote chars).

Now, download the .jar file from Sourceforge and add it to your android project.

You can read my tutorial on how to add .jar file in Android Studio project.

You can read your .csv file as shown below.

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
    // nextLine[] is an array of values from the line
    System.out.println(nextLine[0] + nextLine[1] + "etc...");
}

Or, if you might just want to slurp the whole lot into a List, just call readAll()

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List myEntries = reader.readAll();

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