0

The app wants to store data about a jump (length, height, time) Whenever I try to read my file I get this exception in the line "File directory = context.getFilesDir();"

java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getFilesDir()' on a null object reference"

I don't really know what to put in the context, so it's not null.

Thanks in advance!

public class Save {

static private String savedData;
private static Context context;
static String stringJump;

public static void Save(Jump jump) {
    savedData += jump.getLength() + " ";
    savedData += jump.getHeight() + " ";
    savedData += jump.getTime() + " ";
    FileOutputStream outputStream;
    String filename = "savedJump";

    try {
        outputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
        outputStream.write(savedData.getBytes());
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    stringJump = read_file(context, filename);
    Toast.makeText(context, stringJump, Toast.LENGTH_SHORT).show();
}


public static String read_file(Context context, String filename) {
    File directory = context.getFilesDir();
    File file = new File(directory, filename);
    return file.toString();
}

}

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Florian Jäger
  • 157
  • 1
  • 14
  • 1
    you only pass the `Context` into `read_file` but not into `Save` ...while within an `Activity` the `Context` is commonly `this` or in a `Fragment` it's `this.getContext()` ...to use `Save` (the default constructor) as a method which saves, also appears questionable. – Martin Zeitler Aug 22 '18 at 13:16
  • where is context initialized? – Jens Aug 22 '18 at 13:17
  • BTW do not catch the base Class `Exception`! Only catch checked exception which are thown in the try block. They you can see that the NPE is also thrown in the Save. And also take care of Java naming convention. Method names should start with lower case character – Jens Aug 22 '18 at 13:18
  • Don't use a static context. You might end up with memory leaks (for instance, if you assign it a context from an Activity and later destroy that Activity). As for your question, you're not assigning a value to the context variable. – Ricardo Costeira Aug 22 '18 at 13:19
  • Change `Save.Save(Jump)` to `Save.Save(Context,Jump)` and get rid of the static context. – Thomas S.E. Aug 22 '18 at 13:22
  • @Jens, I don't think this is a duplicate... OP wants to know how to deal with the Context, not the NPE itself. – Ricardo Costeira Aug 22 '18 at 13:26
  • Thank for the answers, it worked perfectly! Can anyone of you write it as an answer, so that I can accept it? – Florian Jäger Aug 22 '18 at 13:26

0 Answers0