1

I need to import a csv file into sqlite database as a table. There are a lot of data in this csv file. I would like to know if there is a way to import such a lot of data programmatically in Kotlin way. I would appreciate any answer and comment.

{Edited} I tried to open a csv file but it shows "open failed" however there is no error showing in logcat. I have no idea where I did mistake. This is the code I tried.

DatabaseHelper Class

class DataBaseHelper(val context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {

companion object{

    private val DATABASE_NAME = "CSV2SQL"
    private val DATABASE_VERSION = 1

    private val TABLE_NAME = "table1"
    private val COL_ID = "Id"
    private val COL_COMPANY = "Company"
    private val COL_PRODUCT = "Product"
    private val COL_PRICE = "Price"
}
    override fun onCreate(db: SQLiteDatabase) {
        val CREATE_PRODUCTS_TABLE = ("CREATE TABLE " +
                TABLE_NAME + "("
                + COL_ID + " INTEGER PRIMARY KEY," +
                COL_COMPANY + " TEXT" +
                COL_PRODUCT + "TEXT" +
                COL_PRICE + "TEXT" +")")
        db.execSQL(CREATE_PRODUCTS_TABLE)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME)
        onCreate(db)
    }

    fun getAllProducts(): java.util.ArrayList<HashMap<String, String>> {
        val proList: java.util.ArrayList<HashMap<String, String>>
        proList = java.util.ArrayList()
        val selectQuery = "SELECT  * FROM $TABLE_NAME"
        val db = this.writableDatabase
        val cursor = db.rawQuery(selectQuery, null)
        if (cursor.moveToFirst()) {
            do {
                //Id, Company,Name,Price
                val map = HashMap<String, String>()
                map["Id"] = cursor.getString(0)
                map["Company"] = cursor.getString(1)
                map["Name"] = cursor.getString(2)
                map["Price"] = cursor.getString(3)
                proList.add(map)
            } while (cursor.moveToNext())
        }

        return proList
    }



  }

MainActivity Class

 class MainActivity : ListActivity() {

    internal lateinit var lbl: TextView
    internal var db = DataBaseHelper(this)
    internal lateinit var btnimport: Button
    internal lateinit var lv: ListView
    internal lateinit var myList: ArrayList<HashMap<String, String>>
    val requestcode = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val txt = findViewById<TextView>(R.id.txtresulttext)
        val mas = findViewById<Button>(R.id.btnupload)
        lv = getListView()

        mas.setOnClickListener  {
            val fileintent = Intent(Intent.ACTION_GET_CONTENT)
            fileintent.type = "gagt/sdf"
            try {
                startActivityForResult(fileintent, requestcode)
            } catch (e: ActivityNotFoundException) {
                lbl.text = "No activity can handle picking a file. Showing alternatives."
            }
        }
        myList = db.getAllProducts()
        if (myList.size != 0) {
            val lv = getListView()
            var array = arrayOf("Company", "Name", "Price")
            val adapter = SimpleAdapter(this,myList,
                R.layout.v, array,intArrayOf(R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice))
            setListAdapter(adapter)
            lbl.text = ""
        }

    }

    override fun  onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (data == null)
            return
            if (requestCode <= requestcode){

            val filepath = data.data!!.path
            val db = db.getWritableDatabase()
            val tableName = "table1"
            db.execSQL("delete from $tableName")
            try {
                if (resultCode == Activity.RESULT_OK) {
                    try {
//                        db = DBHelper(applicationContext)
                        val file = FileReader(filepath!!)

                        val buffer = BufferedReader(file)
                        val contentValues = ContentValues()
                        var line = ""
                        db.beginTransaction()

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

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


                            contentValues.put("Company", company)
                            contentValues.put("Name", Name)
                            contentValues.put("Price", Price)
                            db.insert(tableName, null, contentValues)
                            lbl.text = "Successfully Updated Database."
                        }
                        db.setTransactionSuccessful()
                        db.endTransaction()
                    } catch (e: IOException) {
                        if (db.inTransaction())
                            db.endTransaction()
                        val d = Dialog(this)
                        d.setTitle(e.message.toString() + "first")
                        d.show()
                        // db.endTransaction();
                    }

                } else {
                    if (db.inTransaction())
                        db.endTransaction()
                    val d = Dialog(this)
                    d.setTitle("Only CSV files allowed")
                    d.show()
                }
            } catch (ex: Exception) {
                if (db.inTransaction())
                    db.endTransaction()

                val d = Dialog(this)
                d.setTitle(ex.message.toString() + "second")
                d.show()
                // db.endTransaction();
            }

        }
        myList = db.getAllProducts()
        if (myList.size != 0) {
            val lv = getListView()
            var array = arrayOf("Company", "Name", "Price")
            val adapter = SimpleAdapter(this,myList,
                R.layout.v, array,intArrayOf(R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice))
            setListAdapter(adapter)
            lbl.text = "Data Imported"
        }
    }

This is the error message, Open Failed

Zin Min Oo
  • 33
  • 6
  • 1
    You say that you "do not know where to start", but at least show that you could open a file and iterate through the lines of the CSV and that you can open the sqlite database connection. If you cannot do those things, it is best to research those separately before asking about. Otherwise this is essentially asking for someone to write all the code for you. – C Perkins Jul 31 '19 at 17:51
  • The code looks like C#, not Kotlin. That's a big hurdle to helping you. Besides, if you cannot identify the error messages or a more specific reason why the code doesn't work, then it is difficult to help. You say that it is because your CSV has many rows, but the code loops through all lines of the input file, so that should not be the problem. Please provide actual code which you have tried and exactly why it is not working, including error messages and a description of what happens. – C Perkins Aug 01 '19 at 03:00
  • Just added the kotlin code that I really tried and it cannot open csv file . @CPerkins – Zin Min Oo Aug 01 '19 at 09:18
  • I'm guessing this is a file permission problem, but the precise error is not visible in the image. The logcat probably doesn't have details because the code is catching the exception and displaying it in the dialog... but it does not show enough detail. See https://stackoverflow.com/questions/36750664/no-such-file-or-directory-error-on-filereader-android – C Perkins Aug 01 '19 at 17:08
  • Thanks for your help. Now I use "InputStreamReader" instead of "FileReader" according to the post that you provided, debug some errors and everything is fine now :) @CPerkins – Zin Min Oo Aug 02 '19 at 04:09

1 Answers1

0

Changed the use of "Read Text Class" from "FileReader" to "InputStreamReader".

class MainActivity : ListActivity() {

internal lateinit var lbl: TextView
internal lateinit var db: DataBaseHelper
internal lateinit var btnimport: Button
internal lateinit var lv: ListView
internal lateinit var myList: ArrayList<HashMap<String, String>>
val requestcode = 1

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    db = DataBaseHelper(this)
    lbl = TextView(this)
    lbl = findViewById<TextView>(R.id.txtresulttext)
    val mas = findViewById<Button>(R.id.btnupload)
    lv = getListView()



    mas.setOnClickListener  {
        val fileintent = Intent(Intent.ACTION_GET_CONTENT)
        fileintent.type = "text/csv"
        try {
            startActivityForResult(fileintent, requestcode)
        } catch (e: ActivityNotFoundException) {
            lbl.text = "No activity can handle picking a file. Showing alternatives."
        }
    }
    myList = db.getAllProducts()
    if (myList.size != 0) {
        val lv = getListView()
        var array = arrayOf("Company", "Product", "Price")
        val adapter = SimpleAdapter(this,myList,
            R.layout.v, array,intArrayOf(R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice))
        setListAdapter(adapter)
        lbl.text = ""
    }

}

override fun  onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (data == null)
        return
        if (requestCode <= requestcode){
        val filepath = data.data!!.path
            println(filepath)
            val inputStream = FileInputStream(filepath)//String? to InputString
            println(inputStream)
            val db = db.getWritableDatabase()
        val tableName = "table1"
        db.execSQL("delete from $tableName")
        try {
            println("gg")
            if (resultCode == Activity.RESULT_OK) {
                try {
                    val file = InputStreamReader(inputStream)//use InputStreamReader

                    val buffer = BufferedReader(file)
                    val contentValues = ContentValues()
                    db.beginTransaction()
                    while (true){
                        val line = buffer.readLine()
                        if(line==null) break
                        val str = line.split(",".toRegex(), 3)
                            .toTypedArray()  

                        val Company = str[0].toString()
                        val Product = str[1].toString()
                        val Price = str[2].toString()

                        contentValues.put("Company", Company)
                        contentValues.put("Product", Product)
                        contentValues.put("Price", Price)
                        db.insert(tableName, null, contentValues)

                        lbl.text = "Successfully Updated Database."
                    }

                    db.setTransactionSuccessful()
                    db.endTransaction()
                } catch (e: IOException) {
                    if (db.inTransaction())
                        db.endTransaction()
                    val d = Dialog(this)
                    d.setTitle(e.message.toString() + "first")
                    d.show()
                }

            } else {
                if (db.inTransaction())
                    db.endTransaction()
                val d = Dialog(this)
                d.setTitle("Only CSV files allowed")
                d.show()
            }
        } catch (ex: Exception) {
            if (db.inTransaction())
                db.endTransaction()

            val d = Dialog(this)
            d.setTitle(ex.message.toString() + "second")
            d.show()
        }

    }
    myList = db.getAllProducts()
    if (myList.size != 0) {
        val lv = getListView()
        var array = arrayOf("Company", "Product", "Price")
        val adapter = SimpleAdapter(this,myList,
            R.layout.v, array,intArrayOf(R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice))
        setListAdapter(adapter)
        lbl.text = "Data Imported"
    }
}
}
Zin Min Oo
  • 33
  • 6