Read CSV File From assets Folder in Android Kotlin.

 Hello Everyone,

Today we are going to see how to read csv file from assets in android.



We will read csv without any library or plugin.

Step 1 : Create an assets folder and paste the CSV file.

Right Click app folder > New > Folder > assets Folder.

Copy the CSV File in the Assets Folder.

Step 2 : Copy this Following Code in  MainActivity.kt

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

val minput = InputStreamReader(assets.open("Category.csv"))
val reader = BufferedReader(minput)

var line : String?
var displayData : String = ""

while (reader.readLine().also { line = it } != null){
val row : List<String> = line!!.split(",")
displayData = displayData + row[0] + "\t" + row[1] + "\n"
}

var txtData = findViewById(R.id.data) as TextView
txtData.text = displayData
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/data"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Post a Comment

0 Comments