Answer the question
In order to leave comments, you need to log in
Why does a NullPointerException occur when working with files?
Good day to all!
Why does this type of error
pop up 02-25 21:13:41.714 16207-16207/com.example E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
While trying to initialize a file
File file = new File(getActivity().getFilesDir(), "myfile");
public class onWriteFile extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
File file = new File(getActivity().getFilesDir(), "myfile");
if (file.exists() == false) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("onWriteFile", "Файл не готов, создание нового файла для записи");
}
FileOutputStream f = null;
try {
f = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ObjectOutputStream s = null;
try {
s = new ObjectOutputStream(f);
} catch (IOException e) {
e.printStackTrace();
}
try {
s.writeObject(array); //Я записываю List
} catch (IOException e) {
e.printStackTrace();
}
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void voids) {
super.onPostExecute(voids);
Log.e("onWriteFile", "onPostExecute прошел");
}
}
Answer the question
In order to leave comments, you need to log in
Well, you put a breakpoint on the line with the creation of the file. See what getActivity() returns
Then read about the life cycle of a fragment, and when an activity is attached to it. Or else how to think why getActivity () can return null.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question