Store the sqlite Database into google drive - android

I have tried many example and did not find any good solution.
I want to store the data of my app to store in sqlite database then sync it with the google drive account of the user who installed the app.
There is also a button which will show the data from google drive and user can edit and update the data so the updated data is then store in the google drive.
I'm new in Android development please help me.
I also have applied the following example but did not succeed.
https://github.com/seanpjanson/GDAADemo
Create / Edit / Retrieve DB file with GDAA (Google Drive Api for Android)
Unpredictable result of DriveId.getResourceId() in Google Drive Android API
https://github.com/googledrive/android-quickstart
Thanks

first create a db backup in SD-card using below line
Driver_utils.create_backup(SettingActivity.this);
**add below dependencies in build.gradle **
compile 'com.google.code.gson:gson:2.2.+'
compile 'com.google.android.gms:play-services-drive:10.0.1'`
in_drive.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (Utils.isInternetWorking()) {
File directorys = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Databackup");
if (directorys.exists()) {
String json = preferences_driverId.getString("drive_id", "");
DriveId driveId = gson.fromJson(json, DriveId.class);
//Update file already stored in Drive
Driver_utils.trash(driveId, google_api_client);
// Create the Drive API instance
Driver_utils.creatBackupDrive(SettingActivity.this, google_api_client);
dialog.dismiss();
Toast.makeText(getApplicationContext(), R.string.backupss, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), R.string.inportfirest, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), R.string.nointe, Toast.LENGTH_LONG).show();
}
}
});
**And for Restore use this **
restore_from_drive.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Launch user interface and allow user to select file
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(new String[]{"application/zip"})
.build(google_api_client);
try {
startIntentSenderForResult(
intentSender, REQ_CODE_OPEN, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.w(TAG, e.getMessage());
}
dialog.dismiss();
}
});
#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 (!google_api_client.isConnecting() && !google_api_client.isConnected()) {
google_api_client.connect();
}
}
}
if (requestCode == REQ_CODE_OPEN && resultCode == RESULT_OK) {
DriveId mSelectedFileDriveId = data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
Log.e("DriveID ---", mSelectedFileDriveId + "");
Gson gson = new Gson();
String json = gson.toJson(mSelectedFileDriveId); // myObject - instance of MyObject
editor_drive = preferences_driverId.edit();
editor_drive.putString("drive_id", json).commit();
Log.e(TAG, "driveId this 1-- " + mSelectedFileDriveId);
if (Utils.isInternetWorking()) {
//restore Drive file to SDCArd
Driver_utils.restoreDriveBackup(SettingActivity.this, google_api_client, GOOGLE_DRIVE_FILE_NAME, preferences_driverId, mfile);
Driver_utils.restore(SettingActivity.this);
} else {
Toast.makeText(getApplicationContext(), R.string.nointernets, Toast.LENGTH_LONG).show();
}
}
}
**Make a static Driver_utils class **
public class Driver_utils {
public static DriveFile mfile;
public static GoogleApiClient api;
public static DriveId driveId;
public static Context ctxs;
public static SharedPreferences preferences_driverId;
public static SharedPreferences.Editor editor;
private static final String GOOGLE_DRIVE_FILE_NAME = "Databackup";
public static void restoreDriveBackup(Context ctx, GoogleApiClient apis, String GOOGLE_DRIVE_FILE_NAME, SharedPreferences preferences_driverIds, DriveFile mfiles) {
mfile = mfiles;
api = apis;
preferences_driverId = preferences_driverIds;
Query query = new Query.Builder()
.addFilter(Filters.eq(SearchableField.TITLE, GOOGLE_DRIVE_FILE_NAME))
.build();
Drive.DriveApi.query(api, query).setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
#Override
public void onResult(DriveApi.MetadataBufferResult metadataBufferResult) {
Gson gson = new Gson();
String json = preferences_driverId.getString("drive_id", "");
DriveId driveId = gson.fromJson(json, DriveId.class);
Log.e("driveId put", "" + driveId);
Log.e("filesize in cloud ", +metadataBufferResult.getMetadataBuffer().get(0).getFileSize() + "");
metadataBufferResult.getMetadataBuffer().release();
mfile = Drive.DriveApi.getFile(api, driveId);
mfile.open(api, DriveFile.MODE_READ_ONLY, new DriveFile.DownloadProgressListener() {
#Override
public void onProgress(long bytesDown, long bytesExpected) {
Log.e("Downloading..", "" + bytesDown + "/" + bytesExpected);
}
})
.setResultCallback(restoreContentsCallback);
}
});
}
static final private ResultCallback<DriveApi.DriveContentsResult> restoreContentsCallback =
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.e("Unable to open,try", "data");
return;
}
File sd = Environment.getExternalStorageDirectory();
String backupDBPath = "/Databackup.zip";
File imgFile = new File(sd, backupDBPath);
Log.e("FILE EXIST", imgFile.exists() + "");
if (!imgFile.exists())
try {
imgFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
imgFile = new File(imgFile.getAbsolutePath());
DriveContents contents = result.getDriveContents();
try {
FileOutputStream fos = new FileOutputStream(imgFile.getAbsolutePath());
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream in = new BufferedInputStream(contents.getInputStream());
byte[] buffer = new byte[1024];
int n, cnt = 0;
while ((n = in.read(buffer)) > 0) {
bos.write(buffer, 0, n);
cnt += n;
Log.e("buffer: ", buffer[0] + "");
Log.e("buffer: ", "" + buffer[1]);
Log.e("buffer: ", "" + buffer[2]);
Log.e("buffer: ", "" + buffer[3]);
bos.flush();
}
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Unzip when download from drive
try {
String dest_file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Databackup";
String src_location = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Databackup.zip";
Decompress.unzip(new File(src_location), new File(dest_file_path));
} catch (Exception e) {
e.printStackTrace();
}
}
};
public static void creatBackupDrive(Context ctx, GoogleApiClient apis) {
ctxs = ctx;
api = apis;
Drive.DriveApi.newDriveContents(api).setResultCallback(contentsCallback);
}
final public static ResultCallback<DriveApi.DriveContentsResult> contentsCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.e(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("application/zip")
.setStarred(true).build();
// create a file on root folder
Drive.DriveApi.getRootFolder(api)
.createFile(api, changeSet, result.getDriveContents())
.setResultCallback(fileCallback);
}
};
final public static ResultCallback<DriveFolder.DriveFileResult> fileCallback = new ResultCallback<DriveFolder.DriveFileResult>() {
#Override
public void onResult(DriveFolder.DriveFileResult result) {
preferences_driverId = ctxs.getSharedPreferences("ID", MODE_PRIVATE);
editor = preferences_driverId.edit();
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create the file");
return;
}
driveId = result.getDriveFile().getDriveId();
Log.e(TAG, "Created a file with content: " + driveId);
Gson gson = new Gson();
String json = gson.toJson(driveId); // myObject - instance of MyObject
editor.putString("drive_id", json).commit();
Log.e(TAG, "driveId " + driveId);
mfile = result.getDriveFile();
mfile.open(api, DriveFile.MODE_WRITE_ONLY, new DriveFile.DownloadProgressListener() {
#Override
public void onProgress(long bytesDownloaded, long bytesExpected) {
Log.e(TAG, "Creating backup file" + bytesDownloaded + "/" + bytesExpected);
}
}).setResultCallback(contentsOpenedCallback);
}
};
final public static ResultCallback<DriveApi.DriveContentsResult> contentsOpenedCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error opening file");
return;
}
String sd = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DiaryDatabackup.zip";
Log.e("DB FILE NAME---", sd + "");
DriveContents contents = result.getDriveContents();
BufferedOutputStream out = new BufferedOutputStream(contents.getOutputStream());
byte[] buffer = new byte[1024];
int n;
try {
FileInputStream is = new FileInputStream(sd);
BufferedInputStream in = new BufferedInputStream(is);
while ((n = in.read(buffer)) > 0) {
out.write(buffer, 0, n);
Log.e("Backing up...", "Backup");
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
contents.commit(api, null).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
Log.e("Backup completed!", "complete"+status);
}
});
}
};
public static void trash(DriveId dId, GoogleApiClient apis) {
api = apis;
try {
Log.e(TAG,"Goes in trans" );
DriveFile sumFile = dId.asDriveFile();
com.google.android.gms.common.api.Status deleteStatus =
sumFile.delete(api).await();
if (!deleteStatus.isSuccess()) {
Log.e(TAG, "Unable to delete app data.");
} else {
// Remove stored DriveId.
preferences_driverId.edit().remove("drive_id").apply();
}
Log.d(TAG, "Past sums deleted.");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void restore(Context ctx) {
OutputStream myOutput;
String dbpath = "//data//" + ctx.getPackageName() + "//databases//databaseName.db";
String sdpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Databackup";
File directorys = new File(sdpath + "/backup_sd");
if (directorys.exists()) {
try {
myOutput = new FileOutputStream(Environment.getDataDirectory()
+ dbpath);
// Set the folder on the SDcard
File directory = new File(sdpath + "/backup_sd");
// Set the input file stream up:
InputStream myInputs = new FileInputStream(directory.getPath());
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = myInputs.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close and clear the streams
myOutput.flush();
myOutput.close();
myInputs.close();
Toast.makeText(ctx, R.string.successss, Toast.LENGTH_LONG)
.show();
} catch (FileNotFoundException e) {
Toast.makeText(ctx, ctx.getString(R.string.err), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(ctx, ctx.getString(R.string.err), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.e("NO DB YET ", "Created");
Toast.makeText(ctx, R.string.savesome, Toast.LENGTH_LONG).show();
}
}
public static void create_backup(Context ctx) {
InputStream myInput;
String dbpath = "//data//" + ctx.getPackageName() + "//databases//databaseName.db";
String sdpath_createbackup = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Databackup";
File file = new File(sdpath_createbackup);
if (!file.exists())
file.mkdirs();
try {
myInput = new FileInputStream(Environment.getDataDirectory()
+ dbpath);
// Set the output folder on the Scard
File directory = new File(file + "/backup_sd");
// Create the folder if it doesn't exist:
if (!directory.exists()) {
directory.createNewFile();
}
// Set the output file stream up:
OutputStream myOutput = new FileOutputStream(directory.getPath());
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[100024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close and clear the streams
myOutput.flush();
myOutput.close();
myInput.close();
Toast.makeText(ctx, R.string.backups, Toast.LENGTH_LONG)
.show();
} catch (FileNotFoundException e) {
Toast.makeText(ctx, ctx.getString(R.string.err), Toast.LENGTH_LONG).show();
Log.e("error", e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(ctx, ctx.getString(R.string.err), Toast.LENGTH_LONG).show();
Log.e("error 1", e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
String src_file_path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Databackup";
String destination_location = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Databackup.zip";
Decompress.backupfolder(new File(src_file_path), new File(destination_location));
}
}
And You Need Decomposer file just create and Copy this
public class Decompress {
public static boolean unzip(File zipfile, File directory) {
BufferedReader br = null;
try {
ZipFile zfile = new ZipFile(zipfile);
Enumeration<? extends ZipEntry> entries = zfile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
File file = new File(directory, entry.getName());
if (entry.isDirectory()) {
file.mkdirs();
} else {
file.getParentFile().mkdirs();
InputStream in = zfile.getInputStream(entry);
copy(in, file);
in.close();
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return true;
}
public static boolean backupfolder(File directory, File zipfile) {
try {
URI base = directory.toURI();
Deque<File> queue = new LinkedList<>();
queue.push(directory);
OutputStream out = new FileOutputStream(zipfile);
Closeable res = out;
ZipOutputStream zout = new ZipOutputStream(out);
res = zout;
while (!queue.isEmpty()) {
directory = queue.pop();
for (File kid : directory.listFiles()) {
String name = base.relativize(kid.toURI()).getPath();
if (kid.isDirectory()) {
queue.push(kid);
name = name.endsWith("/") ? name : name + "/";
zout.putNextEntry(new ZipEntry(name));
} else {
zout.putNextEntry(new ZipEntry(name));
copy(kid, zout);
zout.closeEntry();
}
}
}
res.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
while (true) {
int readCount = in.read(buffer);
if (readCount < 0) {
break;
}
out.write(buffer, 0, readCount);
}
}
private static void copy(File file, OutputStream out) throws IOException {
InputStream in = new FileInputStream(file);
try {
copy(in, out);
} finally {
in.close();
}
}
private static void copy(InputStream in, File file) throws IOException {
OutputStream out = new FileOutputStream(file);
try {
copy(in, out);
} finally {
out.close();
}
}
}

My answer assumes that you have a keystore file to sign your app with. If you don't, this link shows you how.
The next thing you need to do is to download the Android and Google play Services SDKs and get an Android certificate, as described here
Now your app should be able to access the Google Drive APIs.
In your activity, create these variables
/**
* Handle access to Drive resources/files.
*/
DriveResourceClient mDriveResourceClient;
/**
* Base folder. This is where the backup will be created
*/
DriveFolder baseFolder;
/**
* Request code for google sign-in, to be used for result of Drive sign-in
* Can be any suitable value
*/
protected static final int REQUEST_CODE_SIGN_IN = 0;
/**
* String variables to hold file names, file paths etc.
*/
static final String BACK_UP = <NAME OF BACKUP FILE CREATED ON DRIVE> ;
static final String dbPath = <PATH TO YOUR DATABASE>;
static final String DATABASE_NAME = <NAME OF YOUR DATABASE>;
/*
* This text view is used to show the output from various operations
*/
private TextView tvDriveResult;
When the user starts the backup process call the function singIn()
/**
* Starts the sign-in process and initializes the Drive client.
*/
private void singIn() {
Set<Scope> requiredScopes = new HashSet<>(2);
requiredScopes.add(Drive.SCOPE_FILE);
GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
if (signInAccount != null && signInAccount.getGrantedScopes().containsAll(requiredScopes)) {
initializeDriveClient(signInAccount);
} else {
GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.build();
GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
}
The singIn() function will handle a user sign - in by starting Google Sign in Client. You will need to handle the result of this client. Use the following code.
/**
* Handles resolution callbacks.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
if (resultCode != RESULT_OK) {
/* Sign-in may fail or be cancelled by the user. For this sample, sign-in is
* required and is fatal. For apps where sign-in is optional, handle appropriately
*/
Log.e(TAG, "Sign-in failed.");
return;
}
Task<GoogleSignInAccount> getAccountTask =
GoogleSignIn.getSignedInAccountFromIntent(data);
if (getAccountTask.isSuccessful()) {
initializeDriveClient(getAccountTask.getResult());
} else {
Log.e(TAG, "Sign-in failed.");
tvDriveResult.append("Sign-in failed\n");
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
After sign-in has been successfully completed, the drive client is initialised above by calling the initializeDriveClient(GoogleSignInAccount signInAccount) function.
/**
* Continues the sign-in process, initializing the Drive clients with the current
* user's account.
*/
private void initializeDriveClient(GoogleSignInAccount signInAccount) {
mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);
mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);
onDriveClientReady();
}
After the drive client is set up, onDriveClientReady() is called. This function proceeds to create / restore your back-up. The functionality here is very simple a. Get the base folder of the user's Google Drive account. b. Check if a back-up file exists. c. If yes, copy that backup to the local database file (over write complete file). d. If no, copy the local database file to the user's Google Drive base folder. You can add some finesse to this logic if you wish. My code is to help you understand the process.
/**
* Called after the user has signed in and the Drive client has been initialized.
*/
private void onDriveClientReady(){
/* Initialise the root folder. */
/* Since the tasks are executed in a separate execution threads, the remaining tasks are called from within each other */
getRootFolder();
}
The getRootFolder() function proceeds as follows
private void getRootFolder() {
/* Get the app folder */
Task<DriveFolder> appFolderTask = mDriveResourceClient.getRootFolder();
appFolderTask
.addOnSuccessListener(this, new OnSuccessListener<DriveFolder>() {
#Override
public void onSuccess(DriveFolder driveFolder) {
tvDriveResult.append("Root folder found\n");
baseFolder = driveFolder;
/* Base folder is found, now check if backup file exists */
checkForBackUp();
/* Use this to delete files. Remember to comment out the line able it */
/* listFilesInBaseFolder(); */
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
tvDriveResult.append("Root folder not found, error: " + e.toString() + "\n");
}
});
}
There is also a function in here called listFilesInBaseFolder() to delete (permanently delete not simply trash) all files you created. It has been commented out in. Use it in case you want to delete files you created, use with caution. As far as I can tell it works only on files that were created by your application.
Check for backup.
private void checkForBackUp() {
/* Build a query */
Query query = new Query.Builder()
.addFilter(Filters.eq(SearchableField.TITLE, BACK_UP))
.build();
/* Query contents of app folder */
Task<MetadataBuffer> queryTask = mDriveResourceClient.queryChildren(baseFolder, query);
/* Check for result of query */
queryTask
.addOnSuccessListener(this, new OnSuccessListener<MetadataBuffer>() {
#Override
public void onSuccess(MetadataBuffer metadataBuffer) {
/* if count is 0, the file doesn't exist */
if (metadataBuffer.getCount() == 0){
tvDriveResult.append("File " + BACK_UP + " not found\n");
/* Make file backup */
backUpDatabase();
} else {
tvDriveResult.append(metadataBuffer.getCount() + " Instances of file " + BACK_UP + " found\n");
Metadata metadata = metadataBuffer.get(0);
restoreBackUp(metadata.getDriveId().asDriveFile());
}
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
tvDriveResult.append("Could not search for file, error: " + e.toString() + "\n");
}
});
}
restoreBackUp(DriveFile driveFile) will over write the local database file with the file found on Goole Drive.
private void restoreBackUp(DriveFile driveFile) {
tvDriveResult.append("Restoring from backup\n");
/* Get the path of the local backup */
File dbFileOld = new File(dbPath + DATABASE_NAME);
/* Check of dbFileExists on device, delete if it does because it needs to be completely over written */
if (dbFileOld.exists()){
dbFileOld.delete();
}
File dbFileNew = new File(dbPath + DATABASE_NAME);
/* File input stream from database to read from */
final FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(dbFileNew);
} catch (FileNotFoundException e) {
tvDriveResult.append("Could not get input stream from local file\n");
return;
}
/* Task to open file */
Task<DriveContents> openFileTask =
mDriveResourceClient.openFile(driveFile, DriveFile.MODE_READ_ONLY);
/* Continue with task */
openFileTask.continueWithTask(new Continuation<DriveContents, Task<Void>>(){
#Override
public Task<Void> then(#NonNull Task<DriveContents> task) throws Exception {
DriveContents backupContents = task.getResult();
InputStream inputStream = backupContents.getInputStream();
tvDriveResult.append("Attempting to restore from database\n");
byte[] buffer = new byte[4096];
int c;
while ((c = inputStream.read(buffer, 0, buffer.length)) > 0){
fileOutputStream.write(buffer, 0, c);
}
fileOutputStream.flush();
fileOutputStream.close();
fileOutputStream.flush();
fileOutputStream.close();
tvDriveResult.append("Database restored\n");
/* Return statement needed to avoid task failure */
Task<Void> discardTask = mDriveResourceClient.discardContents(backupContents);
return discardTask;
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
tvDriveResult.append("Could not read file contents\n");
}
});
}
And lastly, backUpDatabase() creates a backup of your local database.
private void backUpDatabase() {
tvDriveResult.append("Creating Drive back-up");
/* get the path of the local backup */
File dbFile = new File(dbPath + DATABASE_NAME);
/* Check of dbFileExists on device */
if (! dbFile.exists()){
tvDriveResult.append("Local database not found?!\n");
return;
}
/* File input stream from database to read from */
final FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(dbFile);
} catch (FileNotFoundException e) {
tvDriveResult.append("Could not get input stream from local file\n");
return;
}
/* Task to make file */
final Task<DriveContents> createContentsTask = mDriveResourceClient.createContents();
tvDriveResult.append("Creating a back-up of the Database File\n");
Tasks.whenAll(createContentsTask).continueWithTask(new Continuation<Void, Task<DriveFile>>() {
#Override
public Task<DriveFile> then(#NonNull Task<Void> task) throws Exception {
/* Retrieved the drive contents returned by the Task */
DriveContents contents = createContentsTask.getResult();
/* Output stream where data will be written */
OutputStream outputStream = contents.getOutputStream();
/* File output stream */
tvDriveResult.append("Attempting to write\n");
byte[] buffer = new byte[4096];
int c;
while ((c = fileInputStream.read(buffer, 0, buffer.length)) > 0){
outputStream.write(buffer, 0, c);
}
outputStream.flush();
outputStream.close();
fileInputStream.close();
tvDriveResult.append("Database written\n");
/* Save the file, using MetadataChangeSet */
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(BACK_UP)
.setMimeType("application/x-sqlite3")
.setStarred(false)
.build();
return mDriveResourceClient.createFile(baseFolder, changeSet, contents);
}
})
/* Task successful */
.addOnSuccessListener(new OnSuccessListener<DriveFile>() {
#Override
public void onSuccess(DriveFile driveFile) {
tvDriveResult.append("Back up file created\n");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
tvDriveResult.append("Could not create back up file\n");
}
});
}
And that is it! This should get you started with basic operations. I recommend going through Google's Developer Guide for a deeper dive.

Related

how to stop duplicate file uploade on google drive?

I'm uploading files to Google Drive using Google Drive api . I would like to know, how i can put a check for duplicate files. Because currently when my service runs, it uploads the file to google drive which was already uploaded before,
Here's my code:
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
public ArrayList songsList = new ArrayList();
private static final String TAG = "drive-quickstart";
private GoogleApiClient mGoogleApiClient;
public static ArrayList<File> listAllMusicFiles = new ArrayList<File>();
public static final String EXISTING_FOLDER_ID = "0B2EEtIjPUdX6MERsWlYxN3J6RU0";
private SharedPreferences sharedPreferences;
/**
* DriveId of an existing file to be used in file operation samples..
*/
public static final String EXISTING_FILE_ID = "0ByfSjdPVs9MZTHBmMVdSeWxaNTg";
/**
* Extra for account name.
*/
protected static final String EXTRA_ACCOUNT_NAME = "account_name";
/**
* Request code for auto Google Play Services error resolution.
*/
protected static final int REQUEST_CODE_RESOLUTION = 1;
/**
* Next available request code.
*/
protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;
private static final String DRIVE_ID = "driveId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final File mainDir = new File(Environment.getExternalStorageDirectory()
.getPath());
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
loadSdcardfiles(mainDir);
}
/**
* Create a new file and save it to Drive.
*/
private void saveFileToDrive(final File file) {
Log.i(TAG, "Creating new contents.");
Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(
new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
final DriveContents driveContents = result
.getDriveContents();
// Otherwise, we can write our data to the new contents.
Log.i(TAG, "New contents created.");
// Get an output stream for the contents.
OutputStream outputStream = result.getDriveContents()
.getOutputStream();
// Write the bitmap data from it.
try {
#SuppressWarnings("resource")
FileInputStream fileInputStream = new FileInputStream(
file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setTitle(file.getName()).build();
// create a file on root folder
Drive.DriveApi
.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient,
metadataChangeSet, driveContents)
.setResultCallback(fileCallback);
try {
} catch (Exception e) {
Log.i(TAG, "Failed to launch file chooser.");
}
}
});
}
private void loadSdcardfiles(File aFile) {
if (aFile.isFile()) {
if (aFile.getAbsolutePath().endsWith(".mp3")) {
listAllMusicFiles.add(aFile);
}
} else if (aFile.isDirectory()) {
File[] listOfFiles = aFile.listFiles();
if (listOfFiles != null) {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
loadSdcardfiles(listOfFiles[i]);
}
}
} else {
}
}
}
#SuppressWarnings("unchecked")
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API).addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
}
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
}
}
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
GoogleApiAvailability.getInstance()
.getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Toast.makeText(this, "API client connected" + listAllMusicFiles.get(0),
1000).show();
if (listAllMusicFiles.size() == 0) {
return;
} else {
for (int i = 0; i < listAllMusicFiles.size(); i++) {
saveFileToDrive(listAllMusicFiles.get(i));
}
}
}
#Override
public void onConnectionSuspended(int cause) {
Toast.makeText(this, "GoogleApiClient connection suspended", 1000)
.show();
}
// private void storeSumFileId(DriveId driveId) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putString(DRIVE_ID, driveId.encodeToString());
// editor.apply();
//
// }
// final private ResultCallback<DriveResource.MetadataResult> metadataRetrievedCallback = new ResultCallback<DriveResource.MetadataResult>() {
// #Override
// public void onResult(DriveResource.MetadataResult result) {
// if (!result.getStatus().isSuccess()) {
// Log.v(TAG, "Problem while trying to fetch metadata.");
// return;
// }
//
// Metadata metadata = result.getMetadata();
// if (metadata.isTrashed()) {
// Log.v(TAG, "Folder is trashed");
// } else {
// Log.v(TAG, "Folder is not trashed");
// }
//
// }
// };
final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the file");
return;
}
showMessage("Created a file with content: "
+ result.getDriveFile().getDriveId());
// storeSumFileId(result.getDriveFile().getDriveId());
}
};
}
i found the following links, but was unable to use it in my code :
Google Drive Android API - Check if folder exists
https://developers.google.com/drive/android/trash#trash_or_untrash_a_file_or_folder
Can anyone tell me how to make ckeck of existing File on drive?
Thanks.

Read from sqlite db in Drive and write it to local db - Android

I am developing an application which requires sqlite database to be backed up to Google Drive (which I accomplished). Now I want to restore that database back into my application and load it at runtime from SD card.
I am reading the contents of database from Google Drive using android-demo/RetrieveContentsActivity on GitHub and I am using the following code to write it back in my database
ListView onItemClickListener
Drive.DriveApi
.getFile(api,
mResultsAdapter.getItem(position).getDriveId())
.openContents(api, DriveFile.MODE_READ_ONLY, null)
.setResultCallback(contentsOpenedCallback);
ResultCallBack
final private ResultCallback<ContentsResult> contentsOpenedCallback = new ResultCallback<ContentsResult>() {
#Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
return;
}
if (GetFileFromDrive(result)) {
Toast.makeText(getApplicationContext(), "File restored",
Toast.LENGTH_LONG).show();
}
}
};
GetFileFromDrive
private boolean GetFileFromDrive(ContentsResult result) {
Contents contents = result.getContents();
InputStream mInput = contents.getInputStream();
OutputStream mOutput;
boolean restoreSuccess = false;
try {
mOutput = new FileOutputStream(getDatabasePath(DB_NAME));
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0) {
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mInput.close();
mOutput.close();
restoreSuccess = true;
} catch (FileNotFoundException e) {
// TODO: Log exception
Log.e("error_filenotfound", "" + e.getLocalizedMessage());
} catch (IOException e) {
// TODO: Log Exception
Log.e("error_io", "" + e.getLocalizedMessage());
}
return restoreSuccess;
}
The problem is that it deletes the already existing data in my sqlite and empties my sqlite completely. I have tried to find this issue on Google but none came close to helping me.
This guy - Google Drive Android api - Downloading db file from drive - is trying to do the same but he says that he replaced openContents with open. I tried that but it gives an error that The method open(GoogleApiClient, int, null) is undefined for the type DriveFile.
Any sort of help will be appreciated, please. I have been stuck on this for almost a week now and I am getting annoyed.
Let's assume that you downloaded you DB to Drive.
Now, how we get it inside you app:
This example contain FragmentActivity, with GUI. But, you can easy adapt it it to silent download.
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_CODE_SUCCESS:
// Called after a file is saved to Drive.
if (resultCode == RESULT_OK) {
finish();
} else {
finish();
}
break;
case REQUEST_CODE_OPENER:
if (resultCode == RESULT_OK){
//Toast.makeText(this, R.string.pref_data_drive_import_success, Toast.LENGTH_LONG).show();
DriveId driveId = data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
DriveFile file = driveId.asDriveFile();
processDriveFile(file);
} else {
Toast.makeText(this, R.string.pref_data_drive_import_error, Toast.LENGTH_LONG).show();
finish();
}
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult result) {
// Called whenever the API client fails to connect.
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()){
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
finish();
} catch (IntentSender.SendIntentException e){
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "API client connected.");
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
//.setMimeType(new String[] { "application/x-sqlite3" })
.build(mGoogleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.w(TAG, "Unable to send intent", e);
}
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
Now, we do check, if selected file is our database and replase it
private void processDriveFile(DriveFile file){
Log.i(TAG, "processDriveFile started");
file.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null)
.setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(#NonNull DriveApi.DriveContentsResult driveContentsResult) {
if (!driveContentsResult.getStatus().isSuccess()){
Log.i(TAG, "Failed to create new contents.");
Toast.makeText(getApplicationContext(), "Import DB error", Toast.LENGTH_LONG).show();
finish();
return;
}
Log.i(TAG, "New contents created.");
DriveContents driveContents = driveContentsResult.getDriveContents();
InputStream inputStream = driveContents.getInputStream();
String dbDir = context.getDatabasePath("oldDbName.db").getParent();
String newFileName = "newDbName.db";
Log.i(TAG, "dbDir = " + dbDir);
// Deletion previous versions of new DB file from drive
File file = new File(dbDir + "/" + newFileName);
if (file.exists()){
Log.i(TAG, "newDbName.db EXISTS");
if (file.delete()){
Log.i(TAG, "newDbName.db DELETING old file....");
} else {
Log.i(TAG, "newDbName.db Something went wrong with deleting");
Toast.makeText(getApplicationContext(), "Import DB error", Toast.LENGTH_LONG).show();
finish();
}
}
try {
OutputStream output = new FileOutputStream(file);
try {
try {
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Import DB error", Toast.LENGTH_LONG).show();
finish();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Import DB error", Toast.LENGTH_LONG).show();
finish();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Import DB error", Toast.LENGTH_LONG).show();
finish();
}
}
// Check if file really match our DB
// Connection it to custom SqliteOpenHelper
ImportDBManager importDBManager = new ImportDBManager(context);
importDBManager.open();
// We have some System table in DB with 1 row in it for this goal
// So, we check if there is data in it
List<DataModelSystem> dataModelSystem = importDBManager.getSystemSingleRow(1);
importDBManager.close();
if (dataModelSystem.size() > 0){
Log.i(TAG, "DB MATCH!");
String mainDbName = context.getDatabasePath(DatabaseHelper.DB_NAME).toString();
String newDbName = context.getDatabasePath(ImportDatabaseHelper.DB_NAME).toString();
File oldDbFile = new File(mainDbName);
File newDbFile = new File(newDbName);
if (newDbFile.exists()){
Log.i(TAG, "newDbName.db EXISTS");
if (oldDbFile.delete()){
Log.i(TAG, "newDbName.db DELETING old file....");
try {
copyFile(newDbFile, oldDbFile);
Log.i(TAG, "success! New database");
Toast.makeText(getApplicationContext(), "Import OK!!!!1", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Import DB error", Toast.LENGTH_LONG).show();
Log.i(TAG, "fail! old database will remain");
e.printStackTrace();
finish();
}
} else {
Log.i(TAG, "newDbName.db Something went wrong with deleting");
Toast.makeText(getApplicationContext(), "Import DB error", Toast.LENGTH_LONG).show();
finish();
}
}
} else {
Log.i(TAG, "db not Match!");
Toast.makeText(getApplicationContext(),"Import DB error", Toast.LENGTH_LONG).show();
finish();
}
}
});
finish();
}
// Replacing old file
private static void copyFile(File src, File dst) throws IOException {
Log.i(TAG, "src = " + src.getAbsolutePath());
Log.i(TAG, "dst = " + dst.getAbsolutePath());
FileInputStream var2 = new FileInputStream(src);
FileOutputStream var3 = new FileOutputStream(dst);
byte[] var4 = new byte[1024];
int var5;
while((var5 = var2.read(var4)) > 0) {
var3.write(var4, 0, var5);
}
var2.close();
var3.close();
}
It is 100% working
Nobody's gonna run and debug your code. Here are a few points to help:
1/ Assuming your app uploaded your DB file (GooDrive does not care if it is DB or anything else - just a byte stream). Record/save it's DriveId - it should look like "DriveId:CAES........"
2/ check if the file in GooDrive (drive.google.com) has the size you expect. You can also use third party SQLite web app to check the state of your DB file in the Drive (make sure you created/uploaded it with correct MIME type).
3/ In you Android app, pass your saved DriveId to this method:
private static GoogleApiClient mGAC;
...
/*******************************************************************
* get file contents
* #param dId file driveId
*/
static void read(DriveId dId) {
byte[] buf = null;
if (mGAC != null && mGAC.isConnected() && dId != null) {
DriveFile df = Drive.DriveApi.getFile(mGAC, dId);
df.open(mGAC, DriveFile.MODE_READ_ONLY, null)
.setResultCallback(new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult rslt) {
if ((rslt != null) && rslt.getStatus().isSuccess()) {
DriveContents cont = rslt.getDriveContents();
byte[] buf = UT.is2Bytes(cont.getInputStream());
int size = buf.length;
cont.discard(mGAC); // or cont.commit(); they are equiv if READONLY
}
}
});
}
}
4/ check the size/state/content of the byte buffer you downloaded. You can write it back to the DB file as well.
These steps should get you closer to resolving your error.
Good Luck

google drive application in android to upload photos to the drive.The code is listed below

I wrote code in 3 different classes.
First for connection
Second for taking images from gallery
Third for uploading images to the drive.
I made a Googleapiclient object as static in the first class like
static GoogleApiClient getmGoogleapiclient()
{
return mGoogleApiClient;
} without null value i got mGoogleApiClient
in the 3rd class, while executing this line:
Drive.DriveApi.newDriveContents(Bqdriveactivity.getmGoogleapiclient()).setResultCallback(new ResultCallback<DriveContentsResult>() {
the problem occurs, no error inside the pgm but it won't execute.
This is the code
public class Uploadimage extends Activity
{
private static final String TAG = "Jimmy-android-drive-application";
private static final int REQUEST_CODE_CREATOR = 0;
// private GoogleApiClient mGoogleApiClient ;
public Bitmap mBitmapToSave;
ArrayList<Bitmap> bpobj=new ArrayList<Bitmap>();
String images;
ArrayList<String> stringArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bqdriveactivity);
stringArray= getIntent().getStringArrayListExtra("imagearray");
if(stringArray!=null){
Iterator<String> i = stringArray.iterator();
do
{
images=i.next();
Log.e("name is: ",images);
mBitmapToSave=BitmapFactory.decodeFile(images);
if(mBitmapToSave==null){
Log.e("ERROR? : ","mBitmap is null");
}
else
{
//Log.e("ERROR","not null");
}
try {
Thread thread = new Thread(new myThread());
thread.start();
} catch (Exception e) {
e.printStackTrace();
}
}while (i.hasNext());
}
}
class myThread implements Runnable {
#Override
public void run() {
saveFileToDrive(mBitmapToSave);
}
}
public void saveFileToDrive( Bitmap bp) {
// Start by creating a new contents, and setting a callback.
Log.i(TAG, "Creating new contents.");
final Bitmap image = bp;
if(bp==null){
Log.e(TAG,"bitmap is null");
}
else
{
Log.e(TAG,"bitmap is not null");
}
if(Bqdriveactivity.getmGoogleapiclient()==null){
Log.e(TAG,"null client");
}
else
{
Log.e(TAG,"not null");
}
up to here the code executes
Drive.DriveApi.newDriveContents(Bqdriveactivity.getmGoogleapiclient()).setResultCallback(new ResultCallback<DriveContentsResult>() {
public void onResult(DriveContentsResult result) {
Log.i(TAG, "inside drive contents");
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
Log.i(TAG, "New contents created.");
// Get an output stream for the contents.
OutputStream outputStream = result.getDriveContents().getOutputStream();
Log.i("TAG","getoutputstream");
// Write the bitmap data from it.
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
Log.i("TAG","before compress");
image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
Log.i("TAG","after compress");
try {
outputStream.write(bitmapStream.toByteArray());
Log.i("TAG","inside try");
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
// Create the initial metadata - MIME type and title.
// Note that the user will be able to change the title later.
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg").setTitle("Android Photo.png").build();
// Create an intent for the file chooser, and start it.
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(result.getDriveContents())
.build(Bqdriveactivity.getmGoogleapiclient());
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.i(TAG, "Failed to launch file chooser.");
}
}
});
}
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_CODE_CREATOR:
// Called after a file is saved to Drive.
if (resultCode == RESULT_OK) {
Log.i(TAG, "Image successfully saved.");
mBitmapToSave = null;
}
break;
}
}
}

How to set on button backup/restore functionality in sqlite database ?

I want to set on button click events backup my applications data on SD-Card.
This is my code :
shv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(SecondActivity.this, "backup Button press",Toast.LENGTH_LONG).show();
boolean rc = MyDatabaseTools.backup();
System.out.println(rc);
if(rc==true)
{
Toast.makeText(SecondActivity.this, "backup Successfully",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(SecondActivity.this, "backup error",Toast.LENGTH_LONG).show();
}
}
});
I proceed like this :
public class MyDatabaseTools {
private String appName = "";
private String packageName = "";
public static boolean backup() {
boolean rc = false;
boolean writeable = isSDCardWriteable();
if (writeable) {
File file = new File(Environment.getDataDirectory() + "/data/<com.example.judgedetail>/databases/ado.db");
File fileBackupDir = new File(Environment.getExternalStorageDirectory(), "ADOBOOK" + "/backup");
if (!fileBackupDir.exists()) {
fileBackupDir.mkdirs();
}
if (file.exists()) {
File fileBackup = new File(fileBackupDir, "ado.db");
try {
fileBackup.createNewFile();
/*Files.copyFile(file, fileBackup);*/ //got error here dis line not work
rc = true;
} catch (IOException ioException) {
//
} catch (Exception exception) {
//
}
}
}
return rc;
}
private static boolean isSDCardWriteable() {
boolean rc = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
rc = true;
}
return rc;
}
public MyDatabaseTools(final Context context, final String appName) {
this.appName = appName;
packageName = context.getPackageName();
}
}
Files.copyFile(file, fileBackup);
This line got error.
How shall I solve this ?
Please help.
Try this:
public void writeToSD() throws IOException {
File f=new File("/data/data/com.YourPackageName/databases/DBName");
FileInputStream fis=null;
FileOutputStream fos=null;
try{
fis=new FileInputStream(f);
fos=new FileOutputStream("/mnt/sdcard/dump.db");
while(true){
int i=fis.read();
if(i!=-1){
fos.write(i);
}
else{
break;
}
}
fos.flush();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
fos.close();
fis.close();
}
catch(IOException ioe){
System.out.println(ioe);
}
}
}
I don't know where you copied that code from, but either you or the poster missed something. Files.copyFile() is no existing Android API function, and I guess that's what you describe as the line being not working.
You'll have to copy your file using another method, I'd suggest one like this:
https://stackoverflow.com/a/9293885/1691231

Transferring files from usb to internal memory?

I am making a android app when I plug a flash drive into my tablet or phone via OTG usb, it will transfer the files off of it to a specified location. Now, it will transfer if I specify a file name, but how can I get it to transfer all the files without having to specify a name? I am using fileinput/fileoutput with byte array.
#SuppressLint("SdCardPath")
public class filetransfer extends Activity {
Button btnsend;
String extstorage = Environment.getExternalStorageDirectory().toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityfiletransfer);
btnsend = (Button) findViewById(R.id.button1);
final Runtime runtime = Runtime.getRuntime();
try
{
runtime.exec("su -c");
}
catch(Exception e)
{
}
btnsend.setOnClickListener(new View.OnClickListener()
{
Context context = getApplicationContext();
CharSequence scs = "Folder Doesn't Exist, Creating now, Checking for Flash Drive....";
CharSequence mvng = "Folder already exist, checking now for flash drive....";
CharSequence chk1 = "Flash Drive detected, transferring files now.";
CharSequence chk2 = "Flash Drive Is Not Detected";
int duration = Toast.LENGTH_SHORT;
Toast bldng = Toast.makeText(context, scs, duration);
Toast mvfldr = Toast.makeText(context, mvng, duration);
Toast chkffd = Toast.makeText(context, chk1, duration);
Toast chkffd2 = Toast.makeText(context, chk2, duration);
#Override
public void onClick(View arg0)
{
File src = new File(extstorage + "/FILEBACKUP");
File usbdrive = new File(extstorage + "/usbStorage/sda1");
if(!src.exists())
{
src.mkdirs();
bldng.show();
if(!usbdrive.exists())
{
chkffd2.show();
}
else
{
chkffd.show();
copyfiles();
}
}
else
{
mvfldr.show();
if(!usbdrive.exists())
{
chkffd2.show();
}
else
{
chkffd.show();
copyfiles();
}
}
}
private void copyfiles()
{
String pathofd = "/sdcard/usbStorage/sda1";
String internalpath = "/sdcard/FILEBACKUP";
File dir = new File(pathofd);
File[] files = dir.listFiles();
for (File afile : files)
{
if(afile.isFile())
{
copyFile(afile.getAbsolutePath(), internalpath, afile.getName());
}
}
try
{
}
/*OutputStream myoutput = new FileOutputStream("/sdcard/FILEBACKUP");
InputStream myinput = new FileInputStream("/sdcard/usbStorage/");
byte[] buffer = new byte[1024];
int length;
while((length=myinput.read(buffer))>0)
{
myoutput.write(buffer);
}
myoutput.flush();
myoutput.close();
myinput.close();
}*/
catch(Exception e)
{
}
}
private void copyFile(String absolutePath, String internalpath,
String name) {
// TODO Auto-generated method stub
try
{
OutputStream myoutput = new FileOutputStream(extstorage + "/FILEBACKUP/");
InputStream myinput = new FileInputStream(extstorage + "/usbStorage/sda1");
byte[] buffer = new byte[1024];
int length;
while((length=myinput.read(buffer))>0)
{
myoutput.write(buffer, 0, length);
}
myoutput.flush();
myoutput.close();
myinput.close();
}
catch(Exception e)
{
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activityfiletransfer,
menu);
return true;
}
}
Just list the files in the directory:
String pathOfFlashDrive = <path of flash drive goes here>;
String internalPath = <internal destination path goes here>;
File dir = new File( pathOfFlashDrive );
File[] files = dir.listFiles();
for( File aFile : files ) {
if( aFile.isFile() ) {
copyFile( aFile.getAbsolutePath(), internalPath + aFile.getName() );
}
}

Categories

Resources