我正在寫一個記事本應用程序,我正在創建一個create a password
屏幕,直到您創建一個,然後從此彈出一個log in
屏幕。Android無法記住我的文件
下面是一些示例代碼:
File myFile = new File(getFilesDir() + "pass.txt");
if (!myFile.exists()) // if "pass.txt" DOESN'T exist, make them create a password
{
try {
// this writes the password to the "pass.txt" file
// which is the one that is checked to exist.
// after it is written to, it should always exist.
FileOutputStream fos = openFileOutput("pass.txt", Context.MODE_PRIVATE);
fos.write(pass.getBytes());
// this writes the security question to a different file.
fos = openFileOutput("securityQ.txt", Context.MODE_PRIVATE);
fos.write(secQ.getBytes());
// this writes the security answer to a different file.
fos = openFileOutput("securityAnswer.txt", Context.MODE_PRIVATE);
fos.write(secAns.getBytes());
fos.close();
} catch(Exception e) {}
^即在一種方法。然後,在另一個我這樣做:
try { // input the right password to the String data
char[] inputBuffer = new char[1024];
fIn = openFileInput("pass.txt");
isr = new InputStreamReader(fIn);
isr.read(inputBuffer);
data = new String(inputBuffer);
isr.close();
fIn.close();
}catch(IOException e){}
if (password.getText().toString().equals(data)) // if password is right, log in.
{
loggedin();
}
else // if the password entered is wrong, display the right one.
{
TextView scr = (TextView)findViewById(R.id.display);
scr.setText("." + data + "."+'\n'+"." + password.getText().toString() + ".");
}
問題是,即使密碼輸入正確,並顯示證明,用戶無法登錄。
另一個問題是,每當我再次運行應用程序時,它會轉到創建屏幕,這意味着它識別文件不存在(即使我只是寫了它)。
我已經處理了整個項目的文件,它可以跟蹤輸入的文本,以便當您按下按鈕時,它會將文件讀回給您。即使您關閉它,它也會跟蹤您輸入的內容。由於某些原因,密碼的東西不起作用。
下面是會發生什麼情況的圖像(第一.k.
距離"pass.txt"
文件和第二.k.
讀出的數據被從EditText
輸入String
用戶):
解決登錄問題:
String values look the same but don't ".equals()" each other
不得不在密碼用戶輸入上簡單使用.trim()
方法。
我想你應該使用SharedPreferences來保存密碼和用戶名,看看這個:http://developer.android.com/reference/android/content/SharedPreferences。html – Tobiel
@Tobiel:我認爲他應該只保存用戶名的偏好,保存重要信息,如密碼將是不可行的,因爲偏好可以被閱讀 –