2013-01-10 57 views
0

在我的應用程序中,我必須從設置頁面設​​置一個密碼並將其寫入文件,之後當我進入主頁時,如果文件爲空,我必須讀取該文件進入到settinngs頁面,閱讀文件時遇到問題

用於它的代碼.....

try { 
       System.out.println("Enter try block!!!"); 
       FileInputStream fis = openFileInput(FILENAME1); 
       InputStreamReader in = new InputStreamReader(fis); 
       BufferedReader br = new BufferedReader(in); 
       data = br.readLine(); 
       System.out.println("data from settings file"+data); 
       System.out.println("-------1Data Read From File is:1" + data); 
       if(data.equals(null)) 
       { 
        Toast.makeText(getApplicationContext(), "You have to set a password", Toast.LENGTH_SHORT).show(); 
        Intent in1 = new Intent(); 
        in1.setClass(getApplicationContext(), SetteingsPage.class); 
        startActivity(in1); 
       } 
      } catch (Exception e) { 

      } 

如果密碼已經設置,然後將代碼工作properly..But如果它爲null,則不進入設置類...

回答

0

嘗試改變你的if-condition類似的,

if(data == null || data.equals("") || data.equals("null")) 

另外,如果文件不可用,則openFileInput()拋出FileNotFoundException

你必須添加catch子句類似,

catch (FileNotFoundException e) { 

    Toast.makeText(getApplicationContext(), "You have to set a password", Toast.LENGTH_SHORT).show(); 
    Intent in1 = new Intent(); 
    in1.setClass(getApplicationContext(), SetteingsPage.class); 
    startActivity(in1); 
} 
0

我看到兩個選項。首先,如果文件不存在,則不會通過openFileInput,因爲它會引發異常。其次,你可能會得到一個空行,它不是null。你應該嘗試做這樣的事情:

if(data==null || data.equals("")) ... 
0

我敢肯定你會得到一個FileNotFoundException如果當您嘗試閱讀的文件不存在。

試試這段代碼,看看文件是否存在。

File file = getContext().getFileStreamPath(FILENAME1);

if(file.exists()) { ... }