2

I would like to fill RecyclerView with my custom operations.json file which stays in sampledata folder. How can i read that sample json file? My operations.json file just looks like this:

{
  "data" :[
    { "name": "123", "image": "@drawable/ic_cloud_download_black_24dp" },
    { "name": "456", "image": "@drawable/ic_arrow_forward_black_24dp" },
    { "name": "789", "image": "@drawable/ic_photo_camera_black_24dp" },
    { "name": "asd", "image": "@drawable/ic_alarm_off_black_24dp" },
    { "name": "qwe", "image": "@drawable/ic_assignment_black_24dp" },
    { "name": "rty", "image": "@drawable/ic_map_black_24dp" },
    { "name": "asd", "image": "@drawable/ic_sms_black_24dp" },
    { "name": "fgh", "image": "@drawable/ic_print_black_24dp" },
    { "name": "zxc", "image": "@drawable/ic_library_books_black_24dp" },
    { "name": "vbn", "image": "@drawable/ic_settings_black_24dp" },
    { "name": "jkl", "image": "@drawable/ic_android_black_24dp" },
    { "name": "yui", "image": "@drawable/ic_tv_black_24dp" },
    { "name": "ert", "image": "@drawable/ic_exit_to_app_black_24dp" }
  ]
}
elyar abad
  • 771
  • 1
  • 8
  • 27
  • https://stackoverflow.com/questions/13814503/reading-a-json-file-in-android – Rohit Suthar Oct 28 '19 at 03:07
  • Welcome to SO! When you place a question try to add a minimum content: input sample, expected output sample, what did you try, research and where are you stuck. And exactly, what did you try? – David García Bodego Oct 28 '19 at 03:48
  • Hi @DavidGarcíaBodego, sampledata folder is specific directory. I dont know this reading operation doable from that location. Therefore i havent tried anything. Searched over internet but there is no clue about reading file from sampledata folder. – user2537972 Oct 28 '19 at 04:30

3 Answers3

4
  • First Create asset folder
  • Place your json file inside asset folder

    Asset folder

  • Read json file following code

    private fun loadJSONFromAsset(): String? { val json: String? try { val inputStream = activity!!.assets.open("search_key.json") val size = inputStream.available() val buffer = ByteArray(size) inputStream.read(buffer) inputStream.close() json = String(buffer, Charsets.UTF_8) } catch (ex: IOException) { ex.printStackTrace() return null } return json }

  • Parse your json using GSON library

    val data = Gson().fromJson(loadJSONFromAsset(), Data::class.java)

Rafiqul Hasan
  • 3,324
  • 4
  • 20
  • 28
2

You should do step by step as below or watching the tutorial (using Kotlin Language):

  • Create the Assets folder
  • Add your sample_data.json to the Assets folder.
  • Read the JSON from the sample_data.json file.
  • Parse the JSON String to a data Model by using Gson.
John Le
  • 1,116
  • 9
  • 12
0

I dont want to copy json file to assets so, srcDirs better solution for that. Modification can be done in App's Gradle file:

android {
    sourceSets.main.assets.srcDirs += file('sampleData')
}

Later this file can be read as asset file.