-1

I need to load data from a .txt file by using the following method:

 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);
    }
}

When calling the method getTextfromFile();, under the onCreate(); the program crashes, with giving me the following error:

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

I have tried to:

  1. Check if the id is correct.

  2. Made sure that the correct layout is being called by setContentView(R.id.activity_main);

  3. Making sure that the method getTextFromFile(); is being called under the setContentView();

Thanks!

hurkaperpa
  • 131
  • 11
  • clockTxt is null, so R.id.clockText or GUI creation must be wrong. – Joop Eggen May 13 '16 at 08:39
  • make sure that your clockText is inside the right layout (the one created with the onCreate method). As said above, your TextView is not found, which makes it null. – Xema May 13 '16 at 08:52
  • Try to do the findview in the onCreate and pass the textview as an argument in the function `getTextFromFile(TextView tv)`. – michoprogrammer May 13 '16 at 08:53

1 Answers1

1

In a way or another your TextView isn't instantiated. To assert it you can still do something like:

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

Either the right layout isn't included, either the ID of your TextView is wrong.The assert isn't working here though.

Amesys
  • 816
  • 2
  • 10
  • 19
  • I believe that I am calling from a different layout, since I have the `textview` in the `fragment` and trying to create it from the main activity. After trying to call the textview from the fragment's class, the same error still persists. In addition I have done the following statement: `if(clockTxt == null) { Log.d("TextView checking", "textview not found in layout"); } else { clockTxt.setText(contents); }` however, I am not having any output :( Thanks again – hurkaperpa May 13 '16 at 09:28
  • What do you obtain in logcat when you instantiate the textview in the fragment? I think that passing your String "contents" to your fragment to instantiate it there should work. – Amesys May 13 '16 at 09:43