日々是好日~every day is a good day~

日常の中の非日常の備忘録

【Android Studio】データ保存

Android Studio kotlinのメソッドパーツ化
今回はデータ保存です
ゲームのハイスコアのようにアプリを終了しも保持されるsharedPreferencesを使います
sharedPreferencesの詳細はAndroidDevelopersをどうぞ
ここではコピペして使えるように余分な説明は省きます

val sharedPreferences = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE)
var highScore:Int = sharedPreferences.getInt("HiGH_SCORE",0)
if(score > highScore){
     highScoreLavel.setText("High Score : "+score)
     sharedPreferences.edit().putInt("HiGH_SCORE", score).apply()
 }
else{
     highScoreLavel.setText("High Score : " + highScore)
 }

使用例はこちら(前回の画面遷移の例を少し追加修正します)
everydayisagoodday.hatenadiary.com
MainActivity.kt

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView

var score :Int = 0 /*ここで宣言すると他のクラスでも使える*/
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val btPush:Button = findViewById(R.id.btPush)
        val tvCount:TextView = findViewById(R.id.tvCount)
        val btNext:Button = findViewById(R.id.btNext)
        btPush.setOnClickListener {
            score++
            tvCount.text = score.toString()
        }
        btNext.setOnClickListener {
            val intent = Intent(this,NextActivity::class.java)
            startActivity(intent)
        }
    }
}

NextActivity.kt

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView

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

        val tvScore : TextView = findViewById(R.id.tvScore)
        val tvHighscore : TextView = findViewById(R.id.tvHighscore)
        val btBack: Button = findViewById(R.id.btBack)
        val sharedPreferences = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE)
        var highScore:Int = sharedPreferences.getInt("HiGH_SCORE",0)

        tvScore.text = score.toString()

        if(score > highScore){
            tvHighscore.setText("High Score : "+score)
            sharedPreferences.edit().putInt("HiGH_SCORE", score).apply()
        }else{
            tvHighscore.setText("High Score : " + highScore)
        }

        btBack.setOnClickListener {
            score = 0
            val intent = Intent(this,MainActivity::class.java)
            startActivity(intent)
        }
    }
}

実行すると 
ハイスコアがでるとHigh Scoreの表示が更新されます アプリを終了してもハイスコアは保存されています

ちなみに保存されたデータはデバイスのdata/data/パッケージ名(com.example.modeltest)/shared_prefasに設定した名前(GAME_DATA)であります