2013-03-14 69 views
0

参考Best way to store a single user in an Android app?的问题和解答如何存储Android的单用户登录数据?

共享首选项如何实际工作?

我希望做的是:

  • 第一次用户打开应用程序增加了一个登录ID和密码
  • 下一次用户打开应用程序使用以前的ID /密码和数据登录。 (我不想自动登录,因为我的应用程序中的数据会很敏感,因此即使是带手机的朋友也不应该能看到它)。
  • 用户更改此ID /密码的能力

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

+0

你好,我们三个人都试图帮助下面,你会能够upvote有用的答案,并勾选一个,如果它回答你的问题。如果没有,你能否澄清为什么我们可以进一步提供帮助?谢谢! – 2013-03-14 18:46:18

回答

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相同!

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

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);"); 

在这里,我有三个字段,其中列1列2和是具有价值“用户名”和“密码”的字符串。创建完成后,您可以执行查询以满足您的需要。

0

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

相关问题