Question

First off, I am not trying to write to the SDCard. I want to write some information to a file that persists between uses of the app. It is essentially a file to hold favorites of the particular user. Here is what the code looks like:

try {
            File file = new File("favorites.txt");

            if (file.exists()) {
                Log.d(TAG, "File does exist.");
                fis = new FileInputStream(file);
                br = new BufferedReader(new InputStreamReader(fis));
            }
            else {
                Log.d(TAG, "File does not exist.");
                return favDests;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

When running this code, we always get the "File does not exist." message in our DDMS log.

We have also tried the following code to no avail:

try {
            File file = new File(GoLincoln.FAV_DEST_FILE);

            fis = new FileInputStream(file);
            br = new BufferedReader(new InputStreamReader(fis));

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

It is this second portion of code that results in the FileNotFoundException.

I have read multiple tutorials on writing and reading files on Android and I believe I am following them pretty closely, so I am not sure why this code doesn't work successfully. I appreciate any help!

Was it helpful?

Solution

You shouldn't use the File class directly. Use Activity.getCacheDir() to get the cache dir which is specific to your application. Then use new File(cachedir, "filename.tmp") to create the file.

OTHER TIPS

Preferences and SQLLite will both allow you to have persistent data without managing your own files.

To use shared preferences you grab it from your context, then you edit the values like so

mySharedPreferences = context.getSharedPreferences("DatabaseNameWhateverYouWant", 0);
mySharedPreferences.getEditor().putString("MyPreferenceName", "Value").commit();

To get a preference out

mySharedPreferences.getString("MyPreferenceName", "DefaultValue");

This is really the simplest way to do basic preferences, much easier then doing a file. More then strings are supported, most basic data types are available to be added to the Preferences class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top