A
A
Artix2015-02-25 16:19:24
Android
Artix, 2015-02-25 16:19:24

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

Initially, my call to the class responsible for saving the object in the file was written in the fragment's onPause() method; and everything was fine, there were no errors, but this method did not suit me, because the file should be saved by clicking on the listview element, and the listview itself is in another fragment, and when I tried to call the class from another fragment, java.lang.NullPointerException
ended. I decided do something different and add all the code to the AsyncTask, but still crashes with the same error
Here is the code:
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

2 answer(s)
V
Vladimir Abramov, 2015-02-25
@kivsiak

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.

X
xne71247, 2015-02-26
@xne71247

I am newbie. Try wrapping the file initialization in a try catch.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question