Merging two databases in Android - java

In my app I have implemented options to backup and restore the database to a SDcard. When I restore the database, I must have the currently saved data included with the backed up data. How to make this possible?
This is how I am restoring database.
Restore:
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath= "//data//" + "PackageName"
+ "//databases//" + "DatabaseName";
String backupDBPath = "/BackupFolder/DatabaseName";
File backupDB= new File(data, currentDBPath);
File currentDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dest = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(),
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}

Try to attach backed to your current db in this way:
sqlite> ATTACH DATABASE 'testDB1.db' as 'DB1';
sqlite> ATTACH DATABASE 'testDB2.db' as 'DB2';
sqlite> ATTACH DATABASE 'testDB3.db' as 'DB3';
SQLite - ATTACH Database

Related

Restore and delete the old SQLite database with new SQLite database in android

I am developing an app where I have to backup and restore my database. I have wrote the code for backup and it's working but I want to restore the backup database in my app and delete the one which is already present there. Please provide the solution for non rooted android devices.
Thank you!
My backup code:
private void exportDB(){
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "/data/"+getPackageName()+"/databases/"+DatabaseHelper.DATABASE_NAME;
String backupDBPath = "abcrecord.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
} catch(IOException e) {
e.printStackTrace();
}
}
Your code shows that you can backup your database. So for restoring this database we switch the source and destination files as below:
private void RestoreDB(){
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "/data/"+getPackageName()+"/databases/"+DatabaseHelper.DATABASE_NAME;
String backupDBPath = "abcrecord.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(backupDB).getChannel();
destination = new FileOutputStream(currentDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "DB restored!", Toast.LENGTH_LONG).show();
backupDB.delete(); //for deleting the backup database after restoring
} catch(IOException e) {
e.printStackTrace();
}
}

How to upload files (documents)/zip in MSSQL using jdbc?

I'm trying to store documents(doc,ppt,pdf,txt..etc) in MSSQL(server running in AWS). I'm working on the app module (android). I can get the files from the user but I'm not able to upload it to the database.
What I've done so far:
Tried to upload the file directly using setBinaryStream
Tried to upload the fileInputStream using setBinaryStream
No blob type can be declared in this database column
Update
Code Requested:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sm_attachments:
FilePickerDialog filePickerDialog = new FilePickerDialog(SendMailToCustomers.this,properties);
filePickerDialog.setTitle("Select Files");
filePickerDialog.show();
filePickerDialog.setDialogSelectionListener(new DialogSelectionListener() {
#Override
public void onSelectedFilePaths(String[] files) {
for (String file : files) {
Uri uri = Uri.fromFile(new File(file));
try {
File file1 = new File(uri.getPath());
//InputStream inputStream = new FileInputStream(new File(uri.getPath()));
byte[] bytesArray = null;
bytesArray = new byte[(int) file1.length()];
FileInputStream fileInputStream = new FileInputStream(file1);
fileInputStream.read(bytesArray);
String sql = "INSERT INTO Storedata (FileName,MyFile) values (?,?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1,"myNewFile");
//statement.setBinaryStream(2, /*inputStream*/fileInputStream,fileInputStream.available());
statement.setBytes(2, /*inputStream*/bytesArray);
int row = statement.executeUpdate();
if(row>0){
Toast.makeText(SendMailToCustomers.this, "The File was inserted Successfully", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onSelectedFilePaths: Inserted File Successfully");
}
else{
Toast.makeText(SendMailToCustomers.this, "Failed To Insert File", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onSelectedFilePaths: Failed To Insert File");
}
} catch (Exception e) {
Log.d(TAG, "onSelectedFilePaths: "+"Exception - "+e.getMessage()+"\n");
e.printStackTrace();
}
break;
The String[] files - are the selected files(Uri) for upload.
Next is the picture of my SQL Database:
MyFile is varbinary(MAX)
Upon doing this : statement.setBytes(2, /inputStream/bytesArray);
I get the below result. But this is around 433984 byte length i.e. bytes read for one file. How should i go about this?
The BULK IMPORT would not natively be able to do this however if you are on SQL2005 or greater you can use SSIS. The first step would be to perform an Exectute Process Task and use a zip utility to unzip the file. The second step is to use the SSIS Bulk Insert task to push the data into SQL Server.

Saving a sound bite as a ringtone

I am trying to set a .wav file as a ringtone on Android devices. The code below is able to create directories, and the sound file, but seems to have issues actually setting the file as a ringtone, let alone the selected ringtone. After the method ends, I go to ringtones on the device, and the selected ringtone defaults to "None". Any idea what's going on here? I am using the WRITE_EXTERNAL_STORAGE permission in my manifest. Also, the format of the sound bite doesn't matter to me, I don't mind converting anything that needs converted.
Thanks!!
private String saveAs(String fileName) {
int resSound = getContext().getResources().getIdentifier(fileName, "raw", getContext().getPackageName());
// Resolve save path and ensure we can read and write to it
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/media/audio/ringtones/";
File dir = new File(path);
fileName += ".wav";
if (!dir.exists()) {
dir.mkdirs();
}
if(!dir.canRead() || !dir.canWrite()) {
return "Unable to save ringtone.";
}
// Load the audio into a buffer
byte[] buffer;
InputStream fIn = this.context.getBaseContext().getResources().openRawResource(resSound);
int size;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
}
catch (IOException e) {
return "Error opening sound file";
}
File file = new File(dir, fileName);
FileOutputStream save;
try {
save = new FileOutputStream(file);
save.write(buffer);
save.flush();
save.close();
}
catch (FileNotFoundException e) {
return "Error loading sound file.";
}
catch (IOException e) {
return "Unable to save ringtone.";
}
// Register the sound byte with the OS and set its properties
this.context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path + fileName)));
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, getSoundTitle(fileName));
values.put(MediaStore.MediaColumns.SIZE, size);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
values.put(MediaStore.Audio.Media.ARTIST, "Sound Clip");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
Uri uri = this.context.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath()), values);
RingtoneManager.setActualDefaultRingtoneUri(this.context, RingtoneManager.TYPE_RINGTONE, uri);
return "Successfully set ringtone.";
}
For anyone else who runs into this, I figured it out. It's this line.
this.context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path + fileName)));
If anyone happens to know why this is, I'd be very interested to know. Thanks!

is it possible backup and RESTORE a database file in android? non root devices [duplicate]

This question already has answers here:
Backup and restore SQLite database to sdcard
(3 answers)
Closed 8 years ago.
in my app I need get a backup of my database,
but after I'll need restore it again,
i have read somethings, but i do not sure if this is necessary to have a rooted device,
i need backup/restore the all data in non root devices, is it possible?
my first idea was creating a txt file for write the select, and later insert it again.
but i believe this is much "problem" then i don't know if this is possible copy the database and paste in sd card for backup, and copy from sd card and paste in path of database for restore for non root devices.
Here is some code to make it work
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();
}
}

Trying to save SQLite db to sdcard [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Moving my db to sd card not working
I'm trying to save a sqlite file to my sdcard. I'm using the code from this question
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "\\data\\com.test.mytest\\databases\\test_db";
String backupDBPath = "test_db";
File currentDB = new File(data, currentDBPath);
File 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();
}
}
} catch (Exception e) {
}
This is a very highly rated answer, so I would think it should work pretty simply. I get no errors in logcat. I don't see any created directory/created files. I also have the "write to external" permission in my manifest.
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "/data/packagename/databases/DATABASENAME";
String backupDBPath = "/backup/"+"main.db";
File currentDB = new File(data, currentDBPath);
File 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();
} else {
Log.e(TAG, "File does not exist: " + currentDBPath);
}
Don t forget to declare permission in amnifest file
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

Categories