在 SD 卡中备份后,如何从 XML 文件恢复 Android Sharedpreferences?

How to restore Android Sharedpreferences from XML file after making its backup in sd card?

我搜索过这个,但没有得到答案。 我正在开发 Budget 应用程序,其中有两种类型的数据库(Sqlite 和 Shared-preferences)。我可以 BACKUP/RESTORE sdcard 中的 sqlite 数据库,但我不知道如何备份和恢复共享首选项数据库。

我可以备份共享首选项数据库,但不知道如何从 SD 卡恢复它。
数据库名称: 1.magicbox_database.db 是sqlite数据库, 2.magicbox_database_sf.db 是共享首选项数据库

这是两个数据库备份的代码。

if (isStoragePermissionGranted() == true) {
                    try {
                        File sd = Environment.getExternalStorageDirectory();
                        if (sd.canWrite()) {
                            String currentDBPath = "/data/data/" + getPackageName() + "/databases/OLBE_DEMO";
                            String backupDBPath = "magicbox_database.db";
                            File currentDB = new File(currentDBPath);
                            File backupDB = new File(sd, backupDBPath);
                            Toast.makeText(MainActivity.this, "backup creating....", Toast.LENGTH_SHORT).show();
                            if (currentDB.exists()) {
                                FileChannel src = new FileInputStream(currentDB).getChannel();
                                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                                dst.transferFrom(src, 0, src.size());
                                src.close();
                                dst.close();
                                Toast.makeText(MainActivity.this, "Bckup Created !", Toast.LENGTH_SHORT).show();
                                Toast.makeText(MainActivity.this, "magicbox_database.db  in External Storage", Toast.LENGTH_SHORT).show();
                            }


                            String currentDBPath1 = "/data/data/" + getPackageName() + "/shared_prefs/DATABASE.xml";
                            String backupDBPath1 = "magicbox_database_sf.xml";
                            File currentDB1 = new File(currentDBPath1);
                            File backupDB1 = new File(sd, backupDBPath1);
                           // Toast.makeText(MainActivity.this, "backup creating....", Toast.LENGTH_SHORT).show();
                            if (currentDB1.exists()) {
                                FileChannel src1 = new FileInputStream(currentDB1).getChannel();
                                FileChannel dst1 = new FileOutputStream(backupDB1).getChannel();
                                dst1.transferFrom(src1, 0, src1.size());
                                src1.close();
                                dst1.close();
                                //Toast.makeText(MainActivity.this, "Bckup Created !", Toast.LENGTH_SHORT).show();
                                Toast.makeText(MainActivity.this, "magicbox_database_sf.db  in External Storage", Toast.LENGTH_SHORT).show();
                            }

                        }
                    } catch (Exception e) {
                        Toast.makeText(MainActivity.this, "ERROR! backup not created", Toast.LENGTH_SHORT).show();
                    }
                }

此代码用于恢复两者

 if (isStoragePermissionGranted() == true) {
                    try {
                        File sd = Environment.getExternalStorageDirectory();
                        if (sd.canWrite()) {
                            String currentDBPath = "/data/data/" + getPackageName() + "/databases/OLBE_DEMO";
                            String backupDBPath = "magicbox_database.db";
                            File currentDB = new File(currentDBPath);
                            File backupDB = new File(sd, backupDBPath);
                            Toast.makeText(MainActivity.this, "restoring......", Toast.LENGTH_SHORT).show();
                            if (currentDB.exists()) {
                                FileChannel src = new FileInputStream(backupDB).getChannel();
                                FileChannel dst = new FileOutputStream(currentDB).getChannel();
                                dst.transferFrom(src, 0, src.size());
                                src.close();
                                dst.close();
                                Toast.makeText(MainActivity.this, "Your data Restored !", Toast.LENGTH_SHORT).show();
                            }
                            String currentDBPath1 = "/data/data/" + getPackageName() + "/shared_prefs/DATABASE.xml";
                            String backupDBPath1 = "magicbox_database_sf.xml";
                            File currentDB1 = new File(currentDBPath1);
                            File backupDB1 = new File(sd, backupDBPath1);
                            if (currentDB1.exists()) {
                                FileChannel src1 = new FileInputStream(backupDB1).getChannel();
                                FileChannel dst1 = new FileOutputStream(currentDB1).getChannel();
                                dst1.transferFrom(src1, 0, src1.size());
                                src1.close();
                                dst1.close();
                                Toast.makeText(MainActivity.this, "magicbox_database_sf.db  in External Storage", Toast.LENGTH_SHORT).show();
                            }
                        }

                    } catch (Exception e) {
                        Toast.makeText(MainActivity.this, "ERROR! data not restored", Toast.LENGTH_SHORT).show();
                    }
                }

更改在此代码中

 FileChannel src1 = new FileInputStream(backupDB1).getChannel();
 FileChannel dst1 = new FileOutputStream(currentDB1).getChannel();

是的,只是按照 this 获取路径,XML 文件可以根据您的所有偏好轻松提取 - 然后您可以使用此 xml 内容(通过解析)来创建首选项或提取值

XML 看起来像这样:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <int name="Key2" value="100" />
    <long name="Key1" value="99" />
    <string name="Key">Vikesh Dass</string>
</map>

只需解析 xml 即可获取您的数据,这应该很容易:)

对于解析 Xml 你可以使用这个 class:

public class XMLParser {

private static final String ns = null;

public void parse(InputStream in) throws XmlPullParserException, IOException {
    try {
        XmlPullParser parser = Xml.newPullParser();
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        parser.setInput(in, null);
        parser.nextTag();
        readPreferences(parser);
    } finally {
        in.close();
    }
}

private void readPreferences(XmlPullParser parser) throws XmlPullParserException, IOException {
    parser.require(XmlPullParser.START_TAG, ns, "map");
    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            continue;
        }
        String node = parser.getName();
        if (node.equals("string")) {
            readName(parser);
        } else if (node.equals("int")) {
            readValueint(parser);
        } else if (node.equals("long")) {
            readValuelong(parser);
        } else {
            skip(parser);
        }
    }
}

private void readName(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, ns, "string");
    String name = readText(parser);
    parser.require(XmlPullParser.END_TAG, ns, "string");
    //Set the Preference again after it is fetched
}

private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
    String result = "";
    if (parser.next() == XmlPullParser.TEXT) {
        result = parser.getText();
        parser.nextTag();
    }
    return result;
}

private void readValueint(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, ns, "int");
    String ValueData = parser.getAttributeValue(null, "value");
    String ValueKey = parser.getAttributeValue(null, "name");
    //Set the Preference again after it is fetched
}

private void readValuelong(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, ns, "long");
    String ValueData = parser.getAttributeValue(null, "value");
    String ValueKey = parser.getAttributeValue(null, "name");
    //Set the Preference again after it is fetched
}

private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
    if (parser.getEventType() != XmlPullParser.START_TAG) {
        throw new IllegalStateException();
    }
    int depth = 1;
    while (depth != 0) {
        switch (parser.next()) {
            case XmlPullParser.END_TAG:
                depth--;
                break;
            case XmlPullParser.START_TAG:
                depth++;
                break;
        }
    }
}

}

然后从您的 class 调用:

File sd = Environment.getExternalStorageDirectory();
        String backupDBPath1 = "your_backedUpPrefDb.xml";
        File backupDB1 = new File(sd, backupDBPath1);
        InputStream is = new BufferedInputStream(new FileInputStream(backupDB1));
        XMLParser myXMLParser = new XMLParser();
        myXMLParser.parse(is);
        is.close();