Aug 7, 2015

Android: Saving Object on External Storage

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

public void ReadFile() {
        try {
            File f = new File(filename);
            FileInputStream fIn = context.openFileInput(f.getPath());
            ObjectInputStream oIn = new ObjectInputStream(fIn);
            myPost = (ArrayList<Status>) oIn.readObject();
            oIn.close();
            fIn.close();
            Log.d("myLog", "Readed");
        } catch (FileNotFoundException e) {
            WriteFile();
        } catch (Exception e) {
            Log.d("myLog", "Error Read File: " + e.toString());
        }
    }

    public void WriteFile() {
        try {
            File f = new File(context.getFilesDir(), filename);
            f.createNewFile();
            FileOutputStream fOut = context.openFileOutput(filename, Context.MODE_PRIVATE);
            ObjectOutputStream oOut = new ObjectOutputStream(fOut);
            oOut.writeObject(myPost);
            oOut.close();
            fOut.close();
            Log.d("myLog", "Writed");
        } catch (Exception e) {
            Log.d("myLog", "Error Write File" + e.toString());
        }
    }

No comments:

Post a Comment