android应用程序存储,如何在Android应用程序中保存数据

你有两个选择,我会把选择留给你。

>共享首选项

这是一个Android独有的框架,允许您在键值框架中存储原始值(例如int,boolean和String,尽管严格来说String不是基元)。这意味着你给一个值一个名称,例如“homeScore”,并将值存储到此键。

SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putInt("homeScore", YOUR_HOME_SCORE);

// Apply the edits!

editor.apply();

// Get from the SharedPreferences

SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);

int homeScore = settings.getInt("homeScore", 0);

>内部存储

这在我看来,是你可能会寻找。你可以存储任何你想要的文件,所以这给你更多的灵活性。然而,这个过程可能更棘手,因为一切都将被存储为字节,这意味着你必须小心保持读写过程一起工作。

int homeScore;

byte[] homeScoreBytes;

homeScoreBytes[0] = (byte) homeScore;

homeScoreBytes[1] = (byte) (homeScore >> 8); //you can probably skip these two

homeScoreBytes[2] = (byte) (homeScore >> 16); //lines, because I've never seen a

//basketball score above 128, it's

//such a rare occurance.

FileOutputStream outputStream = getApplicationContext().openFileOutput(FILENAME, Context.MODE_PRIVATE);

outputStream.write(homeScoreBytes);

outputStream.close();

现在,您还可以查看External Storage,但我不建议在这种特殊情况下,因为外部存储可能不是以后。 (注意,如果你选择这个,它需要一个权限)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值