Dropbox sync/Google drive,如何上传sqlite数据库

Lun*_*box 1 android

我正在尝试将sqlite数据库文件上传到dropbox.这是我的代码:

public void uploadDb(){
    File public_db_file = null;
    try {
        public_db_file = writeDbToPublicDirectory();
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    DbxFileSystem dbxFs = null;

    try {
        dbxFs = DbxFileSystem.forAccount(mAccount);
    } catch (Unauthorized e1) {
        e1.printStackTrace();
    }

    DbxFile testFile = null;
    try {
        testFile = dbxFs.create(new DbxPath("database_sync.txt"));
    } catch (InvalidPathException e1) {
        e1.printStackTrace();
    } catch (DbxException e1) {
        e1.printStackTrace();
    }
    try {
        testFile.writeFromExistingFile(public_db_file, false);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        testFile.close();
    }

}
Run Code Online (Sandbox Code Playgroud)

编辑(更多代码)

此函数将我的数据库从app私有目录复制到公共目录,以便我可以上传它:

private File writeDbToPublicDirectory() throws IOException {
    // TODO Auto-generated method stub
    File sd = Environment.getExternalStorageDirectory();
    File backupDB = null;
    if (sd.canWrite()) {
        String backupDBPath = "copied_database.db";
        File currentDB = context.getDatabasePath("private_database");
        backupDB = new File(sd, backupDBPath);

        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();
        }
    }
    return backupDB;
} 
Run Code Online (Sandbox Code Playgroud)

问题是,当我检查我的设备保管箱时,文件大小为0字节.该文件是在dropbox上创建的,但我的数据库数据不是.我究竟做错了什么?先感谢您

编辑

我已经决定使用Google云端硬盘可能是更好的选择,但我只能使用示例应用程序上传文本文件.有没有可以用来上传sqlite数据库文件的好教程或资源?我真的很难坚持这一点.请帮助我解决其中任何一个,谢谢你提前

Man*_*ani 11

我能够使用Google Drive API备份数据库.我使用字节数组来复制内容.以下是活动代码,它在Google Drive根文件夹上创建一个新文件并复制sqlite db内容.我已经在需要的地方添加了评论.让我知道它是否有帮助.

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.drive.Contents;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveApi.ContentsResult;
import com.google.android.gms.drive.DriveFolder.DriveFileResult;
import com.google.android.gms.drive.MetadataChangeSet;

import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.MimeTypeMap;

public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {

    private static final String TAG = "MainActivity";
    private GoogleApiClient api;
    private boolean mResolvingError = false;
    private DriveFile mfile;
    private static final int DIALOG_ERROR_CODE =100; 
    private static final String DATABASE_NAME = "person.db";
    private static final String GOOGLE_DRIVE_FILE_NAME = "sqlite_db_backup";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create the Drive API instance
        api = new GoogleApiClient.Builder(this).addApi(Drive.API).addScope(Drive.SCOPE_FILE).
                addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
    }

    @Override
    public void onStart() {
        super.onStart();
        if(!mResolvingError) {
            api.connect(); // Connect the client to Google Drive
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        api.disconnect(); // Disconnect the client from Google Drive 
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.v(TAG, "Connection failed");
        if(mResolvingError) { // If already in resolution state, just return.
            return;
        } else if(result.hasResolution()) { // Error can be resolved by starting an intent with user interaction
            mResolvingError = true;
            try {
                result.startResolutionForResult(this, DIALOG_ERROR_CODE);
            } catch (SendIntentException e) {
                e.printStackTrace();
            }
        } else { // Error cannot be resolved. Display Error Dialog stating the reason if possible.
            ErrorDialogFragment fragment = new ErrorDialogFragment();
            Bundle args = new Bundle();
            args.putInt("error", result.getErrorCode());
            fragment.setArguments(args);
            fragment.show(getFragmentManager(), "errordialog");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == DIALOG_ERROR_CODE) {
            mResolvingError = false;
            if(resultCode == RESULT_OK) { // Error was resolved, now connect to the client if not done so.
                if(!api.isConnecting() && !api.isConnected()) {
                    api.connect();
                }
            }
        }
    }

    @Override
    public void onConnected(Bundle connectionHint) {
        Log.v(TAG, "Connected successfully");

        /* Connection to Google Drive established. Now request for Contents instance, which can be used to provide file contents.
           The callback is registered for the same. */  
        Drive.DriveApi.newContents(api).setResultCallback(contentsCallback);
    }

    final private ResultCallback<ContentsResult> contentsCallback = new ResultCallback<ContentsResult>() {

        @Override
        public void onResult(ContentsResult result) {
            if (!result.getStatus().isSuccess()) {
                Log.v(TAG, "Error while trying to create new file contents");
                return;
            }

            String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("db"); 
            MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                    .setTitle(GOOGLE_DRIVE_FILE_NAME) // Google Drive File name
                    .setMimeType(mimeType)  
                    .setStarred(true).build();
            // create a file on root folder
            Drive.DriveApi.getRootFolder(api)
                    .createFile(api, changeSet, result.getContents())
                    .setResultCallback(fileCallback);   
        }

    };

    final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {

        @Override
        public void onResult(DriveFileResult result) {
            if (!result.getStatus().isSuccess()) {
                Log.v(TAG, "Error while trying to create the file");
                return;
            }
            mfile = result.getDriveFile();
            mfile.openContents(api, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(contentsOpenedCallback);
        }
    };

    final private ResultCallback<ContentsResult> contentsOpenedCallback = new ResultCallback<ContentsResult>() {

        @Override
        public void onResult(ContentsResult result) {

            if (!result.getStatus().isSuccess()) {
                Log.v(TAG, "Error opening file");
                return;
            }

            try {
                FileInputStream is = new FileInputStream(getDbPath());
                BufferedInputStream in = new BufferedInputStream(is);
                byte[] buffer = new byte[8 * 1024];
                Contents content = result.getContents();
                BufferedOutputStream out = new BufferedOutputStream(content.getOutputStream());
                int n = 0;
                while( ( n = in.read(buffer) ) > 0 ) {
                    out.write(buffer, 0, n);
                }

                in.close();
                mfile.commitAndCloseContents(api, content).setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status result) {
                        // Handle the response status
                    }
                });
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    };

    private File getDbPath() {
        return this.getDatabasePath(DATABASE_NAME);
    }

    @Override
    public void onConnectionSuspended(int cause) {
        // TODO Auto-generated method stub
        Log.v(TAG, "Connection suspended");

    }

    public void onDialogDismissed() {
        mResolvingError = false;
    }

    public static class ErrorDialogFragment extends DialogFragment {
        public ErrorDialogFragment() {}

        public Dialog onCreateDialog(Bundle savedInstanceState) {
            int errorCode = this.getArguments().getInt("error");
            return GooglePlayServicesUtil.getErrorDialog(errorCode, this.getActivity(), DIALOG_ERROR_CODE);
        }

        public void onDismiss(DialogInterface dialog) {
            ((MainActivity) getActivity()).onDialogDismissed();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)