1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SharedPreferencesを扱う

Posted at

基本

書き込む

val shardPreferences = this.getPreferences(Context.MODE_PRIVATE)
val shardPrefEditor = shardPreferences.edit()
shardPrefEditor.putString("data", data)
shardPrefEditor.apply()

読み取る

val shardPreferences = this.getPreferences(Context.MODE_PRIVATE)
var data = shardPreferences.getString("data", "[]")

どのActivityからでも閲覧できるようにする

val shardPreferences = this.getSharedPreferences("KEY",Context.MODE_PRIVATE)
val shardPrefEditor = shardPreferences.edit()
shardPrefEditor.putString("data", data)
shardPrefEditor.apply()

JSONArrayとして保存

//arrayList : ArrayList<String>
val jsonArray = JSONArray(arrayList)
shardPrefEditor.putString("data", jsonArray.toString())

JSONArrayをArrayListとして読み取る

private fun loadArrayList(data: String): ArrayList<String> {

val shardPreferences = getSharedPreferences("KEY",Context.MODE_PRIVATE)
val jsonArray = JSONArray(shardPreferences.getString(data, "[]"))
val arrayList : ArrayList<String> = ArrayList()

for (i in 0 until jsonArray.length()) {
    arrayList.add(jsonArray.get(i) as String)
}
        
return arrayList
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?