空对象引用:使用.txt数据填充textView时

时间:2016-05-13 08:26:08

标签: java android xml

我需要使用以下方法load .txt file数据:

 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

  3. 正在调用正确的setContentView(R.id.activity_main);
  4. 确保在getTextFromFile();;

  5. 下调用方法setContentView()

    谢谢!

1 个答案:

答案 0 :(得分:1)

以某种方式,您的TextView未实例化。 要断言它你仍然可以做类似的事情:

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

要么没有包含正确的布局,要么TextView的ID错误。虽然断言在这里不起作用。

相关问题