亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何為應用程序創建簡單的本地備份和恢復?

如何為應用程序創建簡單的本地備份和恢復?

哈士奇WWW 2023-08-04 15:46:42
我有五個 sqlite 數據庫,我希望用戶能夠在手機中進行本地備份,并且可以恢復備份文件。我不知道如何創建這些備份并以編程方式恢復它們。我使用了 github 存儲庫,但它根本不起作用,我需要你的幫助來創建這個備份和恢復過程。感謝您的關注
查看完整描述

2 回答

?
慕桂英4014372

TA貢獻1871條經驗 獲得超13個贊

在您的活動中制作備份和恢復按鈕并定義本地數據庫變量,例如,


private MainDatabase localBackup = new MainDatabase(this);

然后點擊即可進行備份和恢復操作


@Override

public void onClick(View v) {

    final MainDatabase db = new MainDatabase(getApplicationContext());


    switch (v.getId()) {

        case R.id.tvBackUp:

            String outFileName = Environment.getExternalStorageDirectory() + 

File.separator + getResources().getString(R.string.app_name) + File.separator;

            localBackup.performBackup(db, outFileName);

            break;

        case R.id.tvRestore:

            File folder = new File(Environment.getExternalStorageDirectory() + File.separator + getApplicationContext().getResources().getString(R.string.app_name));

            if (folder.exists()) {


                final File[] files = folder.listFiles();


                if (files.length == 0) {

                    Toast.makeText(this, "No any Backup", Toast.LENGTH_SHORT).show();

                } else {

                    localBackup.performRestore(db);

                }

            }


            break;

    }

}

在數據庫文件中制定備份方法


public void performBackup(final MainDatabase db, final String outFileName) {


    File folder = new File(Environment.getExternalStorageDirectory() + File.separator 

+ mContext.getResources().getString(R.string.app_name));


    boolean success = true;

    if (!folder.exists())

        success = folder.mkdirs();

    if (success) {


        final Dialog dialog = new Dialog(mContext);

        dialog.setContentView(R.layout.backup_dialog);

        dialog.getWindow().getAttributes().windowAnimations = 

R.style.PauseDialogAnimation;


dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

        dialog.show();


        Button btnSave = dialog.findViewById(R.id.btnSave);

        Button btnCancel = dialog.findViewById(R.id.btnCancel);

        EditText etName = dialog.findViewById(R.id.etName);

        etName.setInputType(InputType.TYPE_CLASS_TEXT);

        btnSave.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                String m_Text = etName.getText().toString();

                String out = outFileName + m_Text + ".db";


                db.backup(out);

                dialog.dismiss();

            }

        });

        btnCancel.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                dialog.dismiss();

            }

        });

    } else

        Toast.makeText(mContext, "Unable to create directory. Retry", 

Toast.LENGTH_SHORT).show();

}


    public void backup(String outFileName) {


    //database path

    final String inFileName = mContext.getDatabasePath(DATABASE_NAME).toString();


    try {

        File dbFile = new File(inFileName);

        FileInputStream fis = new FileInputStream(dbFile);


        // Open the empty db as the output stream

        OutputStream output = new FileOutputStream(outFileName);


        // Transfer bytes from the input file to the output file

        byte[] buffer = new byte[1024];

        int length;

        while ((length = fis.read(buffer)) > 0) {

            output.write(buffer, 0, length);

        }


        // Close the streams

        output.flush();

        output.close();

        fis.close();


        Toast.makeText(mContext, "Backup Completed", Toast.LENGTH_SHORT).show();


    } catch (Exception e) {

        Toast.makeText(mContext, "Unable to backup database. Retry", 

Toast.LENGTH_SHORT).show();

        e.printStackTrace();

    }

}

以及進行恢復時,詢問用戶要恢復什么備份


public void performRestore(final MainDatabase db) {



    File folder = new File(Environment.getExternalStorageDirectory() + File.separator 

+ mContext.getResources().getString(R.string.app_name));

    if (folder.exists()) {


        final File[] files = folder.listFiles();


        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(mContext, 

 android.R.layout.select_dialog_item);

        for (File file : files)

            arrayAdapter.add(file.getName());

        AlertDialog.Builder builderSingle = new AlertDialog.Builder(mContext);


        builderSingle.setTitle("Select & Restore ");

        builderSingle.setNegativeButton("cancle", (dialog, which) -> 

dialog.dismiss());

        builderSingle.setAdapter(arrayAdapter, (dialog, which) -> {

            try {

                db.importDB(files[which].getPath());

            } catch (Exception e) {

                Toast.makeText(mContext, "Unable to restore. Retry", 

Toast.LENGTH_SHORT).show();

            }

        });


        builderSingle.show();

    } else

        Toast.makeText(mContext, "Backup folder not present.\nDo a backup before a 

restore!", Toast.LENGTH_SHORT).show();

}


 public void importDB(String inFileName) {


    final String outFileName = mContext.getDatabasePath(DATABASE_NAME).toString();


    try {


        File dbFile = new File(inFileName);


        FileInputStream fis = new FileInputStream(dbFile);


        // Open the empty db as the output stream

        OutputStream output = new FileOutputStream(outFileName);


        // Transfer bytes from the input file to the output file

        byte[] buffer = new byte[1024];

        int length;

        while ((length = fis.read(buffer)) > 0) {

            output.write(buffer, 0, length);

        }


        // Close the streams

        output.flush();

        output.close();

        fis.close();


        Toast.makeText(mContext, "Restore Completed", Toast.LENGTH_SHORT).show();


    } catch (Exception e) {

        Toast.makeText(mContext, "Unable to import database. Retry", 

Toast.LENGTH_SHORT).show();

        e.printStackTrace();

    }

}



查看完整回答
反對 回復 2023-08-04
?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

如果您的清單中有的話,Android 已經支持系統自動備份android:allowBackup="true"。如果這還不夠,并且您想在應用程序重新安裝之間手動管理備份,那么您必須將數據庫從context.getDatabasePath("<your-database-name>")外部存儲復制到某個地方,然后在需要時將其復制回來



查看完整回答
反對 回復 2023-08-04
  • 2 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號