Dev/Android

[Android] 안드로이드 SQLite 데이터 백업(Backup), 복원(Restore)

healthyryu 2017. 1. 16. 14:55

Android SQLite 데이터 백업(Backup), 복원(Restore)






버전 : 안드로이드 5.0(Lollipop)

모델 : Asus Fonepad - K00Y



안드로이드 외부 SD 카드에 SQLite 데이터 백업 및 내부 저장소에 복원 기능을 참고해서 앱에 적용했습니다.

현재의 소스를 참고한다면 잘 만들어질 겁니다.


참고로, importDB() 부분은 복원 부분이고

exportDB() 부분은 백업 부분입니다.


그리고 현재 아래의 참고 코드는 백업, 복원 둘다 내부에 저장하고 내부에 복원을 하는 코드입니다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
private void importDB() {
        try {
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();
                if (sd.canWrite()) {
                String currentDBPath = "//data//" + "<package name>"
                        + "//databases//" + "<database name>";
                String backupDBPath = "<backup db filename>"// From SD directory.
                File backupDB = new File(data, currentDBPath);
                File currentDB = new File(sd, backupDBPath);
 
            FileChannel src = new FileInputStream(backupDB).getChannel();
            FileChannel dst = new FileOutputStream(currentDB).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
            Toast.makeText(getApplicationContext(), "Import Successful!",
                    Toast.LENGTH_SHORT).show();
 
        }
    } catch (Exception e) {
 
        Toast.makeText(getApplicationContext(), "Import Failed!", Toast.LENGTH_SHORT)
                .show();
 
    }
}
 
private void exportDB() {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();
 
        if (sd.canWrite()) {
            String currentDBPath = "//data//" + "<package name>"
                    + "//databases//" + "<db name>";
            String backupDBPath = "<destination>";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);
 
            FileChannel src = new FileInputStream(currentDB).getChannel();
            FileChannel dst = new FileOutputStream(backupDB).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
            Toast.makeText(getApplicationContext(), "Backup Successful!",
                    Toast.LENGTH_SHORT).show();
 
        }
    } catch (Exception e) {
 
        Toast.makeText(getApplicationContext(), "Backup Failed!", Toast.LENGTH_SHORT)
                .show();
 
    }
}
cs




백업,복원 참고 : http://stackoverflow.com/a/18322762/3897810


SD 카드 저장 참고 https://goo.gl/YQ7pai

반응형