I’m experimenting with android, and I got to the point where I want to save something to internal memory and read from it, but I’m kind of stuck. I found this article http://developer.android.com/guide/topics/data/data-storage.html#filesInternal and as it suggested I created dummy method :
public void test(){
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
}
Which always throws NullPointerException, anyone knows what I’m missing?Maybe some permission in Androidmanifest.xml ?
QUESTION UPDATE:
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
Above line trows NPE. My class is abstract and its extending Activity, I don’t know if that is relevant or not.
Stack trace :
01-29 22:30:44.575: ERROR/TEST(458): java.lang.NullPointerException
01-29 22:30:44.575: ERROR/TEST(458): java.lang.RuntimeException: java.lang.NullPointerException
It seems that any IO operation throws NPE, I tried this as well :
try {
File myDir = new File(getFilesDir().getAbsolutePath());
String s = "";
FileWriter fw = new FileWriter(myDir + "/Test.txt");
fw.write("Hello World");
fw.close();
BufferedReader br = new BufferedReader(new FileReader(myDir + "/Test.txt"));
s = br.readLine();
// Set TextView text here using tv.setText(s);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
File myDir = new File(getFilesDir().getAbsolutePath());
Throws NPE, I even added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
into Androidmanifest.xml
I’ve made method and pass in Context ctx, but my ctx ends up null, how can I get this variable? set it to which value ?
From extensive googling I found that you need to pass Context to your method, which you initialize in
onCreatemethodContext ctx = getApplicationContext();and you pass it to the rest of the application which needs it.