Saad Ismail
Saad Ismail

Reputation: 1440

Getting a weird filenotfoundexception

I am currently on the beginner level when it comes to Android & I am currently scratching my head over an issue that I am currently facing.

I am creating an Android app to check if "cache.json" exists in the internal storage:

This is the code snippet:

public class ShowClasses extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        filename = "cache.json";
        file = new File(getApplicationContext().getFilesDir(), filename);

        if (file.exists()) {
            System.out.println("EXISTS");
        } else {
            System.out.println("DOES NOT EXIST");
            writeFile();
        }

        readFile();
    }

    public void writeFile() {
        new JsonTask().execute(email);
    }

    public void readFile() {
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        int c;
        result = "";
        try {
            while( (c = fin.read()) != -1){
                result = result + Character.toString((char)c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            fin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return;
    }

    private class JsonTask extends AsyncTask<String, Void, String> {

        protected void onPreExecute() {
            result = ""; // Clear result
            super.onPreExecute();
            pd.setMessage("Please wait");
            pd.setCancelable(false);
            pd.show();
        }

        protected String doInBackground(String... params) {
            return "THIS STRING IS GOING TO BE RETURNED " + params[0];
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);    

            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            FileOutputStream fileout = null;

            try {
                fileout = new FileOutputStream(file);
                fileout.write(result.getBytes());
                //display file saved message
                msg("File saved successfully!");

            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                fileout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (pd.isShowing()){
                pd.dismiss();
            }

        }
    }
}

I have tried to remove un-necessary part of the code so that it is smaller in length.

The actual issue I am facing is when writeFile() & readFile() both are called. I get a FileNotFoundException in readFile() when I open the stream even though the file should be created since writeFile() is called before readFile().

If I writeFile on one execution & then call readFile() on the other, it simply works as it should be.

This is the error that I am facing.

System.err: java.io.FileNotFoundException: /data/user/0/host.timetable.timetablenotifier/files/cache.json (No such file or directory) System.err: at java.io.FileInputStream.open(Native Method)

Any help would be really appreciated.

Thanks

Upvotes: 0

Views: 53

Answers (2)

CommonsWare
CommonsWare

Reputation: 1007218

writeFile() is asynchronous. When that method returns, nothing has happened with respect to this file. At most, onPreExecute() of your JsonTask might be called. So, when you call readFile(), the file will not exist yet.

Beyond that:

  • You have an AsyncTask that you use in writeFile(), but you do your disk I/O in onPostExecute(), and that method is called on the main application thread.

  • You are doing disk I/O on the main application thread in readFile().

  • You catch exceptions, log them, but then continue executing your code, when most of those exceptions mean that the later statements are going to fail as well.

  • Reading in data one int at a time has not been a recommended approach for getting close to 20 years, for performance reasons.

  • You will have multiple issues related to configuration changes, such as screen rotations, as neither your AsyncTask nor your ProgressDialog account for configuration changes

Also:

  • getApplicationContext().getFilesDir() could be replaced by getFilesDir() in onCreate()

  • You do not need createNewFile()

Upvotes: 1

Napster
Napster

Reputation: 1383

AsyncTask runs in a background thread so the other code in the main thread doesn't wait for the execution to complete. In simpler terms, your readFile() method is executed before writeFile() completes and hence there is a FileNotFoundException. What would work for you is if you put the readFile() method at the end of the onPostExecute() method inside your Asynctask

Upvotes: 1

Related Questions