0

参考关于在 Android 应用中存储单个用户的最佳方式的问答?

共享偏好实际上是如何工作的?

我想做的是:

  • 用户首次打开应用程序时会添加登录 ID 和密码
  • 下次用户打开应用程序时使用以前的 id/密码和数据登录。(我不希望自动登录,因为我的应用程序中的数据很敏感,因此即使是使用手机的朋友也不应该看到它。)
  • 用户可以更改此 ID/密码

这可以通过共享首选项实现吗?还是我需要使用 SQLlite?我对 Android 完全陌生,所以如果您附上工作代码和解释,我将不胜感激。

4

3 回答 3

1

只要您愿意在其中存储合理的机密数据,您就可以使用共享偏好来执行此操作。在存储和检索之间您将需要一些共享代码:

final static String pfName = "com.super.stuff.preffile.name";
final static String pfCodeForID = "com.super.stuff.pf.id";
final static String pfCodeForPassword = "com.super.stuff.pf.passwd";
final static String pfNoStringPresent = "NO-STRING-PRESENT-HERE";

final static pfCodes = MODE_PRIVATE; // See http://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String, int)

要存储信息:

String ID = //whatever;
String password = //whatever;

SharedPreferences settings = context.getSharedPreferences(pfName, pfCodes);
SharedPreferences.Editor editor = settings.edit();
editor.putString(pfCodeForID, ID);
editor.putString(pfCodeForPassword, password);
editor.commit();

要检索信息:

SharedPreferences settings = context.getSharedPreferences(pfName, pfCodes);

String ID = editor.getString(pfCodeForID, pfNoStringPresent);
String password = editor.getString(pfCodeForPassword, pfNoStringPresent);

if (ID.contentEquals(pfNoStringPresent) && password.contentEquals(pfNoStringPresent)) {
     // Handle the case of nothing stored, ie get ID and password
     }

显然,如果用户名和密码都与 pfNoStringPresent 相同,则会失败!

如果您担心以这种方式存储敏感数据,那么您需要将其存储在数据库中,或者以某种方式对其进行加密。您将需要确定当信息存储在属于提供您 ID 信息的人的设备上时保护信息的重要性,从手机获取此信息对小偷的重要性等等等

于 2013-03-14T16:40:33.280 回答
0

与 AccountManager 集成,然后使用 setUserData ......这是我认为的最佳方式。:)

于 2014-02-20T18:05:20.557 回答
0

使用 Sqlite,它相当简单。按照这个:

public SQLiteDatabase sampleDB;  
sampleDB =  this.openOrCreateDatabase(TABLE_NAME, MODE_PRIVATE, null);    
sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
                TABLE_NAME+ "(" + COLUMN_ID
                + " integer primary key autoincrement, " + COLUMN1
                + " text not null,"+ COLUMN2
                + " text not null);");

这里我有三个字段,其中 column1 和 column2 是具有值“用户名”和“密码”的字符串。创建完成后,您可以根据需要执行查询。

于 2013-03-14T16:57:59.010 回答