Android Read File From Asset Folder Kotlin

In this post we will see how to read a content of file from android assets folder using koltlin ,

1. Creating Asset Folder


To Create Asset Folder Set Your application hierarchy to android , then right click on your project select New > Folder > Assets Folder after that it will popup another there set target source to main
 


Inside the asset folder i have added a file by name "android_version.json"  we will read the content of this file and set to TextView .

2. XML Layout


Create XML Layout activity_main.xml , this will be set as content view for launcher Activity (MainActivity.kt)

file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="20dp"
        tools:context=".MainActivity">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/textView"
    />

</ScrollView>

3. Activity

  1. Create a koltin class MainActivity.kt and extend it to AppCompatActivity class .
  2. Override onCreate function and set the content of this MainActivity with above defined xml layout (activity_main.xml).
  3. Create a function readFromAsset and set the returned type as string (read value from asset). 
    private fun readFromAsset(): String {
        val file_name = "android_version.json"
        val bufferReader = application.assets.open(file_name).bufferedReader()
        val data = bufferReader.use {
            it.readText()
        }
        Log.d("readFromAsset", data)

        return data;
    }
   4. Inside onCreate Call for readFromAsset and set the returned string from  readFromAsset to textView.

file : MainActivity.kt
package com.tutorialsbuzz.androidreadassetfile

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

        textView.setText(data)

    }


    private fun readFromAsset(): String {
        val file_name = "android_version.json"
        val bufferReader = application.assets.open(file_name).bufferedReader()
        val data = bufferReader.use {
            it.readText()
        }
        Log.d("readFromAsset", data)

        return data;
    }
}



No comments:

Post a comment