有人可以通过非常详细而简单的理解向我解释SharedPreferences在Android中的工作原理吗?

Hen*_*ian 2 android login sharedpreferences

我是Android开发的新手,现在我真的很想学习共享偏好.我用Google搜索了很多次,我认为我并没有完全掌握它.

我相信这个共享首选项将帮助我在登录屏幕活动中存储用户名和密码.谢谢!

Ben*_*ben 13

我制作了一些关于这个视频的视频,作为一份工作的试镜.他们帮我找到了工作,他们仍然可以在Vimeo上找到,所以希望他们可以帮助你.

第1部分:保存数据

第2部分:检索数据

此外,为了它的价值,请小心在SharedPreferences中存储用户名和密码.您可以在那里进行,但请阅读其他SO问题中的风险:在Android应用程序中存储用户设置的最合适方法是什么

  • 谢谢本!我看了你的视频,它让我记得我以前见过你的脸;)!谢谢你的一切! (2认同)

Mar*_* S. 5

对于android,主要有三种基本的数据持久化方式:

  • 共享首选项以保存小块数据
  • 传统文件系统
  • 通过 SQLite 数据库支持的关系数据库管理系统

SharedPreferences 对象帮助您将简单的应用程序数据保存为名称/值对 - 您为要保存的数据指定一个名称,然后它及其值将自动保存到 XML 文件中。要将数据保存在 sharedPreferences 文件中:

  1. 获取 sharedPreferences 文件的一个实例: SharedPreferences appPrefs = getSharedPreferences( or fileName, MODE_PRIVATE);

  2. 创建 SharedPreferences.Editor 对象

  3. 例如,要将字符串值放入 SharedPreferences 对象,请使用 putString() 方法。

  4. 要将更改保存到首选项文件,请使用 commit() 方法

看起来像这样:

// obtain an instance of the SharedPreferences class
preferences = getSharedPreferences(prefFileName, MODE_PRIVATE);
editor = preferences.edit();

// save username String
editor.putString("username", student).commit();
Run Code Online (Sandbox Code Playgroud)

要检索它,请使用 getString() 方法:

preferences.getString(username, null) where null is a default value that will be returned if username key is not found in the file.
Run Code Online (Sandbox Code Playgroud)