透過Key Value的形式來儲存,如果你的資料不太複雜,懶得使用資料庫的話,
可以試著使用SharedPreferences來儲存內容。
以下是一個相當簡單的例子
This file contains 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
SharedPreferences sharedPreferences = getSharedPreferences("data" , MODE_PRIVATE); | |
//取得SharedPreferences , 丟入的參數為("名稱" , 存取權限) | |
sharedPreferences.edit().putInt("score" , 100).apply(); | |
//存入資料,丟入的參數為(key , value) | |
sharedPreferences.getInt("score" , 0); | |
//取出資料, 丟入的參數為(key , 若是沒值,預設為多少) |
透過getSharedPreferences來取得這個檔案的內容,前面的key是由你指定的,
第一次他會創建這個檔案到你的手機之中,之後只要透過key就能開啟該檔案。
MODE_PRIVATE,這個存取權限代表,新丟入的值會取代舊的值。
存入使用put,然後apply,將值存入檔案之中。
取出使用get,記得丟入預設的值(以免檔案中沒有這個值)。
像是遊戲排行榜或是一些簡單的資料可以存在這裡面。
沒有留言:
張貼留言