2016-05-13 68 views
-1

我需要load數據從.txt file通過使用下面的方法:空對象引用:當填充的.txt數據一個TextView

public void getTextFromFile() 
{ 
    File path = getExternalFilesDir(null); 
    File file = new File(path, "alarmString.txt"); 

    int length = (int) file.length(); 

    byte[] bytes = new byte[length]; 

    FileInputStream in = null; 
    try { 
     in = new FileInputStream(file); 

     in.read(bytes); 
     in.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 

    }finally { 


     String contents = new String(bytes); 
     TextView clockTxt = (TextView) findViewById(R.id.clockText); 
     assert clockTxt != null; 
     clockTxt.setText(contents); 
    } 
} 

當調用方法getTextfromFile();,所述onCreate();程序崩潰下,與給我以下錯誤:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference 

我曾嘗試:

  1. 檢查id是否正確。

  2. 確信正確layout正在setContentView(R.id.activity_main);

  3. 確保該方法getTextFromFile();被下setContentView()稱爲調用;

謝謝!

+0

clockTxt爲空,所以R.id.clockText或GUI創建必須是錯誤的。 –

+0

確保您的clockText位於正確佈局(使用onCreate方法創建的佈局)內。如上所述,您的TextView沒有找到,這使得它爲空。 – Xema

+0

嘗試在onCreate中執行findview並將textview作爲參數傳遞給函數getTextFromFile(TextView tv)'。 – michoprogrammer

回答

1

以某種方式您的TextView沒有實例化。 要斷言它仍然可以這樣做:

if(clockTxt == null) 
Log.d("TextView checking", "textview not found in layout"); 

要麼不包含正確的佈局,無論是你的TextView的ID wrong.The斷言這裏沒有工作,雖然。

+0

我相信我是從不同的佈局調用的,因爲我在'fragment'中有'textview'並試圖從主要活動中創建它。在試圖從片段的類中調用textview之後,同樣的錯誤仍然存​​在。另外,我做了以下聲明:'if(clockTxt == null){Log.d(「TextView checking」,「textview not found in layout」); } else { clockTxt.setText(contents);然而,我沒有任何輸出:(再次感謝 – hurkaperpa

+0

當你在實例化片段中的textview時,你在logcat中獲得了什麼?我認爲將你的字符串「內容」傳遞給你的片段來實例化它應該有效。 – Amesys