2013-07-26 45 views
0

我正在寫一個記事本應用程序,我正在創建一個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用戶):

enter image description here

解決登錄問題:

String values look the same but don't ".equals()" each other

不得不在密碼用戶輸入上簡單使用.trim()方法。

+2

我想你應該使用SharedPreferences來保存密碼和用戶名,看看這個:http://developer.android.com/reference/android/content/SharedPreferences。html – Tobiel

+0

@Tobiel:我認爲他應該只保存用戶名的偏好,保存重要信息,如密碼將是不可行的,因爲偏好可以被閱讀 –

回答

2

我會傳遞關於將密碼保存在名爲「pass.txt」的文件中的評論,並只關注技術部分。

File myFile = new File(getFilesDir() + "pass.txt"); 

myFile永遠不會是有效的文件。路徑和文件名之間沒有分隔符/。因爲那永遠不會變,所以下一行會說它不存在並且貫穿整個塊。

您可以輕鬆地修復兩種方式這一個:

File myFile = new File(getFilesDir() + "/pass.txt"); 

僅添加分隔的文件名。

File myFile = new File(getFilesDir(), "pass.txt"); 

這可能是更好的選擇,因爲它使用明確的path, file構造函數。不過,任何一個都沒問題。

+0

**完美**答案。 –

+0

爲此,我會嘗試記錄'data'來查看它實際包含的內容。如果它包含正確的值,則可能需要檢查「display」是否正確。 'setText()'不僅不起作用。 – Geobits

+0

我不明白。您編輯它以顯示您正在寫入一個文件並從另一個文件讀取('pass.txt'和'passB.txt')。我是否按照之前的建議記錄過'data'的值?不要緊,你的文件包含什麼;如果它沒有被正確讀取,它不會等於你輸入的任何內容。同時檢查換行符,空格等。 – Geobits

0

您也可以使用context.openFileInput("pass.txt");並在FileNotFoundException發生時捕獲,此時您可以「假設」該文件實際上不存在。