1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.calculator2;
18
19import java.io.InputStream;
20import java.io.OutputStream;
21import java.io.IOException;
22import java.io.FileNotFoundException;
23import java.io.BufferedInputStream;
24import java.io.BufferedOutputStream;
25import java.io.DataInputStream;
26import java.io.DataOutputStream;
27
28import android.content.Context;
29
30class Persist {
31    private static final int LAST_VERSION = 2;
32    private static final String FILE_NAME = "calculator.data";
33    private Context mContext;
34
35    History history = new History();
36    private int mDeleteMode;
37
38    Persist(Context context) {
39        this.mContext = context;
40    }
41
42    public void setDeleteMode(int mode) {
43        mDeleteMode = mode;
44    }
45
46    public int getDeleteMode() {
47        return mDeleteMode;
48    }
49
50    public void load() {
51        try {
52            InputStream is = new BufferedInputStream(mContext.openFileInput(FILE_NAME), 8192);
53            DataInputStream in = new DataInputStream(is);
54            int version = in.readInt();
55            if (version > 1) {
56                mDeleteMode = in.readInt();
57            } else if (version > LAST_VERSION) {
58                throw new IOException("data version " + version + "; expected " + LAST_VERSION);
59            }
60            history = new History(version, in);
61            in.close();
62        } catch (FileNotFoundException e) {
63            Calculator.log("" + e);
64        } catch (IOException e) {
65            Calculator.log("" + e);
66        }
67    }
68
69    public void save() {
70        try {
71            OutputStream os = new BufferedOutputStream(mContext.openFileOutput(FILE_NAME, 0), 8192);
72            DataOutputStream out = new DataOutputStream(os);
73            out.writeInt(LAST_VERSION);
74            out.writeInt(mDeleteMode);
75            history.write(out);
76            out.close();
77        } catch (IOException e) {
78            Calculator.log("" + e);
79        }
80    }
81}
82