android csv file import 01

Android – How to import CSV in SQLite database

In this post we will see How we can import a CSV file into our Android application’s SQLite database. This is updated post on my previous post on import csv sheets into Android application.

Let’s begin.

The application will be having SQLite database for product information stored in it. We will use this db to import our data into from an excel sheet (CSV file-Comma delimited). Create a new layout file in your project with name main.xml and edit it as below:

res > layout > main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff"
android:orientation="vertical"
android:weightSum="9">

<LinearLayout
android:id="@+id/lvcontainer"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:gravity="start|center_vertical"
android:background="#FFC7C7C7"
android:orientation="horizontal"
android:padding="1dp"
android:weightSum="3">

<TextView
android:id="@+id/txtproductcompany"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="start|center_vertical"
android:text="COMPANY"
android:textColor="#000000"
android:textSize="13sp" />

<TextView
android:id="@+id/txtproductname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="start|center_vertical"
android:padding="3dp"
android:text="PRODUCT"
android:textColor="#000000"
android:textSize="13sp" />

<TextView
android:id="@+id/txtproductprice"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="start|center_vertical"
android:padding="3dp"
android:text="PRICE"
android:textColor="#000000"
android:textSize="13sp" />
</LinearLayout>

<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="@+id/lvcontainer"
android:layout_weight="7.5" />

<TextView
android:id="@+id/txtresulttext"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="@android:id/list"
android:layout_marginLeft="5dp"
android:layout_marginTop="2dp"
android:layout_weight="0.5"
android:gravity="left"
android:text=""
android:textColor="#FFF55F54"
android:textSize="20sp"
android:textStyle="italic|bold" />

<Button
android:id="@+id/btnupload"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="5dp"
android:layout_weight="0.5"
android:background="@android:drawable/btn_default_small"
android:text="UPLOAD" />
</LinearLayout>

Now create a new layout file with name template.xml and edit it as below:

res > layout > template.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<LinearLayout
android:id="@+id/lvh"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:scrollbars="horizontal"
android:background="#ffe6e6e6"
android:weightSum="3" >
<TextView
android:id="@+id/txtproductcompany"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="start|center_vertical"
android:text="COMPANY"
android:textColor="#000000"
android:textSize="13sp" />

<TextView
android:id="@+id/txtproductname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="start|center_vertical"
android:padding="3dp"
android:text="PRODUCT"
android:textColor="#000000"
android:textSize="13sp" />

<TextView
android:id="@+id/txtproductprice"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="start|center_vertical"
android:text="PRICE"
android:padding="3dp"
android:textColor="#000000"
android:textSize="13sp" />

</LinearLayout>

</LinearLayout>

This file will be used for display our products imported from CSV sheet into our Android’s SQLite database.
The first layout file will be our main page for the app.

android csv file import 01

Now let’s do code.

Create a new class file in your project with name DBController.java and edit it as below:

DBController.java:

package com.app.androidexcel;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;

public class DBController extends SQLiteOpenHelper {
private static final String LOGCAT = null;

public DBController(Context applicationcontext) {
super(applicationcontext, "PrdouctDB.db", null, 1); // creating DATABASE
Log.d(LOGCAT, "Created");
}

@Override
public void onCreate(SQLiteDatabase database) {
String query;
query = "CREATE TABLE IF NOT EXISTS proinfo ( Id INTEGER PRIMARY KEY, Company TEXT,Name TEXT,Price TEXT)";
database.execSQL(query);
}

@Override
public void onUpgrade(SQLiteDatabase database, int version_old,
int current_version) {
String query;
query = "DROP TABLE IF EXISTS proinfo";
database.execSQL(query);
onCreate(database);
}

public ArrayList<HashMap<String, String>> getAllProducts() {
ArrayList<HashMap<String, String>> proList;
proList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM proinfo";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
//Id, Company,Name,Price
HashMap<String, String> map = new HashMap<String, String>();
map.put("Id", cursor.getString(0));
map.put("Company", cursor.getString(1));
map.put("Name", cursor.getString(2));
map.put("Price", cursor.getString(3));
proList.add(map);
} while (cursor.moveToNext());
}

return proList;
}

}

This will create the sqlite database in our application.

Now create new class file with name main.java and edit it as below:

main.java:

package com.app.androidexcel;

import android.app.Dialog;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class main extends ListActivity {
TextView lbl;
DBController controller = new DBController(this);
Button btnimport;
ListView lv;
final Context context = this;
ListAdapter adapter;
ArrayList<HashMap<String, String>> myList;
public static final int requestcode = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

lbl = findViewById(R.id.txtresulttext);
btnimport = findViewById(R.id.btnupload);
lv = getListView();

myList = controller.getAllProducts();
if (myList.size() != 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(main.this, myList,
R.layout.template, new String[]{"Company", "Name", "Price"}, new int[]{
R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice});
setListAdapter(adapter);
lbl.setText("");
}

btnimport.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
fileintent.setType("*/*");
try {
startActivityForResult(fileintent, requestcode);
} catch (ActivityNotFoundException e) {
lbl.setText("No app found for importing the file.");
}

}
});
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case requestcode:
String filepath = data.getData().getPath();

if(filepath.toLowerCase().contains("root_path"))
filepath = filepath.replace("root_path","");

controller = new DBController(getApplicationContext());
SQLiteDatabase db = controller.getWritableDatabase();
String tableName = "proinfo";
db.execSQL("delete from " + tableName);
try {
if (resultCode == RESULT_OK) {
try {

FileReader file = new FileReader(filepath);

BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues = new ContentValues();
String line = "";
db.beginTransaction();

while ((line = buffer.readLine()) != null) {

String[] str = line.split(",", 3); // defining 3 columns with null or blank field //values acceptance
//Id, Company,Name,Price
String company = str[0].toString();
String Name = str[1].toString();
String Price = str[2].toString();

contentValues.put("Company", company);
contentValues.put("Name", Name);
contentValues.put("Price", Price);
db.insert(tableName, null, contentValues);
lbl.setText("Successfully Updated Database.");
}
db.setTransactionSuccessful();
db.endTransaction();
} catch (IOException e) {
if (db.inTransaction())
db.endTransaction();
ShowDialog(e.getMessage() + "first");
// db.endTransaction();
}
} else {
if (db.inTransaction())
db.endTransaction();
ShowDialog("Only CSV files allowed");
}
} catch (Exception ex) {
if (db.inTransaction())
db.endTransaction();
ShowDialog(ex.getMessage().toString() + "second");

// db.endTransaction();
}
}
myList = controller.getAllProducts();

if (myList.size() != 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(main.this, myList,
R.layout.template, new String[]{"Company", "Name", "Price"}, new int[]{
R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice});
setListAdapter(adapter);
lbl.setText("Data Imported");
}
}

public void ShowDialog(String message)
{
Dialog d = new Dialog(main.this);
d.setTitle(message);
d.show();
}
}

One important thing over here is, which file explorer you are using. Different file browser passes the file path differently. The problem with previous code was the same. If you don’t use ES file explorer, the file path was with “root_path” name and this needs to be replaced. It is done in above code. Like below:

String filepath = data.getData().getPath();

if(filepath.toLowerCase().contains("root_path"))
filepath = filepath.replace("root_path","");

And this is working with all file explorer. I have tested this with my phone’s default file explorer and it works, as shown in video.

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.androidexcel">

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".main"
android:label="@string/app_name"
android:theme="@android:style/Theme.DeviceDefault.Light.DarkActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Now run the application.

Don’t forget to grant storage permissions:

android csv file import 02

Also see:

  1. Android – Load Imageview from URL in Android
  2. How to create Navigation drawer in Android
  3. Android How to play videos from Storage and Filepath
  4. Android How to play videos using VideoView
  5. Android Exoplayer – How to Play Videos Tutorial
  6. How to use Android SharedPreferences – Example
  7. Android Firebase How to Upload and Retrieve Images
  8. How to create Android Splash Screen Animated
  9. How to create Gradient Android Buttons Different Designs
  10. How to bind Android Gridview from ArrayAdapter List<String>
  11. Android How to Scroll ListView Horizontally and Vertically