AbhishekSaha
AbhishekSaha

Reputation: 745

Android: Access data after app is closed and rebooted

I want to create a hashmap when my app is first booted, and be able to access the data written in that hashmap after the app has been closed from Task Manager. How would I go about that?

Upvotes: 0

Views: 56

Answers (1)

horvste
horvste

Reputation: 636

You have many options:

"Shared Preferences

Store private primitive data in key-value pairs.

Internal Storage

Store private data on the device memory.

External Storage

Store public data on the shared external storage.

SQLite Databases

Store structured data in a private database.

Network Connection

Store data on the web with your own network server."

Since it is a Map it would be easiest to write it to a text file then "recompile" it using some kind of key system, probably JSON or xml.

Read more here: http://developer.android.com/guide/topics/data/data-storage.html

EDIT File saver for Map. You will have to edit this to your needs.

final public class FileHandler {
    final private File folderCreatedDir;
    final private String folderToCreate;
    final private Map<String, String> mapNameToContents;

    public FileHandler(File baseDirectory, String folderToCreate,
            Map<String, String> mapNameToContents) {
        this.folderCreatedDir = new File(baseDirectory + File.separator
                + folderToCreate);
        this.folderToCreate = folderToCreate;
        this.mapNameToContents = mapNameToContents;
    }

    private final void createFolder() {
        folderCreatedDir.mkdir();

    }

    private final void writeMapContents() throws IOException {
        Set<String> keySet = mapNameToContents.keySet();
        for (String key : keySet) {
            writeContents(key, mapNameToContents.get(key));
        }

    }

    private final void writeContents(String key, String contents)
            throws IOException {
        File file = new File(folderCreatedDir + File.separator + key);
        FileOutputStream fileOutput = new FileOutputStream(file);
        if (file.canWrite()) {
            fileOutput.write(contents.getBytes());
            fileOutput.close();
        }
    }

    public void writeAllContents() throws IOException {
        createFolder();
        writeMapContents();
    }

    public StringBuilder getContents(String key) throws IOException {
        BufferedReader rd = new BufferedReader(new FileReader(folderCreatedDir
                + File.separator + key));
        String line = "";
        StringBuilder htmlBuilder = new StringBuilder();
        long bytesRead = 0;
        while ((line = rd.readLine()) != null) {
            htmlBuilder.append(line);
            bytesRead = bytesRead + line.getBytes().length + 2;
        }
        return htmlBuilder;
    }
}

Upvotes: 1

Related Questions