Question

At first I have strong Java knowledege, but however just started with Android.

My Android app is downloading some fairly complex data (texts, dates, images) which I am saving in a custom object. The data need to be refresh from time to time. However usually the data downloaded will not change.

In order to keep the data in memory I am using the Application Object. Unfortunately, it looks like the application object instance is destroyed when the app is killed.

Hence, I was wondering if it would be of good practice to serialize and save my custom object (which is contained in the application object) in the internal storage during onPause(). Obviously, I would then first read from the file in onResume() before reloading from the internet. The idea is also to enable offline viewing.

In longer term the plan is to move the code downloading the date in a background service. As there seems to be many different ways to keep application state in Android, I would like to be be sure that this is the correct way to go.

Was it helpful?

Solution

Try using those methods class to save the Object(s) (implements serialize) you need:

public synchronized boolean save(String fileName, Object objToSave)
    {
        try
        {

            // save to file
            File file = new File(CONTEXT.getDir("filesdir", Context.MODE_PRIVATE) + "/file.file");
            if (file.exists())
            {
                file.delete();
            }

            file.getParentFile().mkdirs();
            file.createNewFile();

            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
            oos.writeObject(objToSave);
            oos.close();

            return true;
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
            return false;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return false;
        }
    }


public synchronized Object load(String fileName)
    {
        try
        {

            File file = new File(CONTEXT.getDir("filesdir", Context.MODE_PRIVATE) + "/file.file");
            if (!file.exists())
            {
                return null;
            }

            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
            savedObj = ois.readObject();
            ois.close();

            return savedObj;
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
            return null;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

You'll need to cast the Object you load(). CONTEXT is an Activity or ApplicationContext to get access to the cachedir. Your could use Environment.getExternalStorageState() instead to get a directory path. DOn't forget to add it "/filename".

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