Created
February 25, 2019 00:23
-
-
Save jabubuck/1d296ebbbb8134ad0e15ecfcfa341b15 to your computer and use it in GitHub Desktop.
Useful Kotlin snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //JSON Load from file to object | |
| private fun loadJSONFromAsset(): JSONObject? { | |
| var json: JSONObject? | |
| try { | |
| val inputStream = applicationContext.assets.open("currencies.json") | |
| val inputString = inputStream.bufferedReader().use{it.readText()} | |
| json = JSONObject(inputString) | |
| } catch (ex: IOException) { | |
| ex.printStackTrace() | |
| return null | |
| } | |
| return json | |
| } | |
| //Download JSON from API | |
| //Add anko dependency if large file to prevent crashing | |
| dependencies { | |
| implementation "org.jetbrains.anko:anko:$anko_version" | |
| } | |
| //Then to read we use | |
| val apiResponse = URL("DATAURL").readText() | |
| //Read and write JSON and strings to Shared prefs | |
| //Declare and Instantiate prefs | |
| lateinit var sharedPref: SharedPreferences | |
| //... | |
| sharedPref = applicationContext.getSharedPreferences("MYPREFS", Context.MODE_PRIVATE) | |
| //Get String | |
| val dataString = sharedPref.getString("STRINGNAME", "") | |
| var dataArray = JSONArray() | |
| //IFJSON | |
| if (!dataString!!.isEmpty()) { | |
| dataArray = JSONArray(dataString) | |
| } | |
| //Update JSON | |
| val json = JSONObject() | |
| json.put("KEY", ITEMTOSTORE) | |
| dataArray.put(json) | |
| //Write to prefs | |
| val newDataString = dataArray.toString() | |
| val editor = sharedPref.edit() | |
| editor.putString("STRINGNAME", newDataString) | |
| editor.apply() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment