baki1995
baki1995

Reputation: 83

Android - Saving data to an internal storage

I'm working on a simple to-do list app, and I'm trying to read/write data from/to internal storage. I'm trying to understand when exactly those read/write methods should be called.

I know that the activity class has an onCreate() method which will be a reasonable location for my read method, but where should I call my write method?

I want to call it when the app closes/ends, so I'd assume onDestory() is a good location, but i heard that onDestroy() may not be a good location for data storage operations and i should use onStop().

Any help or ideas?

Upvotes: 0

Views: 553

Answers (3)

urps
urps

Reputation: 366

Following the table in the Android Developers Guide on the Activity Lifecycle, your app may be killed by the system any time without warning after either onPause() (for Pre-HONEYCOMB devices) or after onStop(). So you probably want to write your data in these methods to make sure nothing gets lost. So for newer devices (API level 11 and up), onStop() should be fine. If your app should run on older devices as well, onPause() would be the best place.

Upvotes: 1

Newkie
Newkie

Reputation: 399

It depends on Application Lifecycle.

This Picture

And see This.

onStop() invokes when user press home button(Hard Key).

And then, if memory insufficient or another reason, Android Memory Manager will kill your app instant and onDestory() will never called.

The best thing you have to is make a button to save datas. Of course, Include onStop() save routine.

Upvotes: 1

Paras Jain
Paras Jain

Reputation: 49

This is Just sample code. But you get the idea. Create a custom method implementing the code below and call it on some events like "onClick" or any other.

File file;
    FileOutputStream strem = null;
    String line = "Hey this is my name";
    try {
        file = new File("sdcard/newFile.txt");
        strem = new FileOutputStream(file);
        byte[] bytes = line.getBytes();
        strem.write(bytes);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            strem.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Upvotes: -1

Related Questions