Hello in my app i'm exporting the sharedPreferences file to my device storge and now, i want to import the file into the app again how can i do that ? here is the code for the export and what i tried to do for to import:
private void saveShared()
{
SharedPreferences prefs = context.getSharedPreferences(MySharedPreferences.MY_TEMP, 1);
File myPath = new File(Environment.getExternalStorageDirectory().toString());
File myFile = new File(myPath, MySharedPreferences.MY_TEMP.toString());
try
{
FileWriter fw = new FileWriter(myFile);
PrintWriter pw = new PrintWriter(fw);
Map<String,?> prefsMap = prefs.getAll();
for(Map.Entry<String,?> entry : prefsMap.entrySet())
{
pw.println(entry.getKey() + ": " + entry.getValue().toString());
}
pw.close();
fw.close();
Toast.makeText(context,
"Shared preferences saved!'",
Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
}
}
#SuppressLint("SdCardPath")
public void importSharedPreferences() {
try {
FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory().toString());
String outFileName = "/data/data/com.bibas.workclocks/databases/"+MySharedPreferences.MY_TEMP.toString();
OutputStream output = new FileOutputStream(outFileName);
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();
} catch (Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG)
.show();
}
}
Related
I'm beginner in android.I'm using below code(Facebook Conceal Library) for encrypt and decrypt video but I dont't know what is Entity exactly?I searched many time on the net and also visited developer.android.com/reference/android/content/Entity but I don't know what should I use for Entity still?
public void testEncrypt()
{
File inputFile = new File("/storage/emulated/0/Download/video1.mp4");
try {
final byte[] encrypt = new byte[(int) inputFile.length()];
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("/storage/emulated/0/Download/", Context.MODE_PRIVATE);
File mypath = new File(directory, "encrypt.mp4");
Crypto crypto = new Crypto(new SharedPrefsBackedKeyChain(this), new SystemNativeCryptoLibrary());
if (!crypto.isAvailable()) {
return;
}
OutputStream fileStream = new BufferedOutputStream(
new FileOutputStream(mypath));
OutputStream outputStream = crypto.getCipherOutputStream(
fileStream, new **Entity()**);
outputStream.write(encrypt);
outputStream.close();
} catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this,"Encrypted",Toast.LENGTH_LONG).show();
}
public Void testDecrypt() {
Crypto crypto = new Crypto(new SharedPrefsBackedKeyChain(this),
new SystemNativeCryptoLibrary());
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("/storage/emulated/0/Download/", Context.MODE_PRIVATE);
File file = new File(directory, "decrypt.mp4");
try {
FileInputStream fileStream = new FileInputStream(file);
InputStream inputStream = crypto.getCipherInputStream(fileStream,
new **Entity()**);
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read;
byte[] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "Decrypted", Toast.LENGTH_LONG).show();
}
am a rookie. The present location of my app folder when installed is in data/data but I want to change the folder location(com.time.notes) to Android/data which is where alot of the folder of the apps I install shows, this is the code am presently trying.
public void backup(String item) {
OutputStream myOutput = null;
InputStream myInput = null;
File directory;
String databasePath = "/data/data/"+getPackageName()+"/databases/Memo.db";
File f = new File(databasePath);
if (f.exists()) {
try {
directory = new File("/mnt/sdcard/"+getResources().getString(R.string.app_name)+"/Backup");
if (!directory.exists())
directory.mkdir();
if (item.equals("Backup")) {
myOutput = new FileOutputStream(directory.getAbsolutePath() + File.separator + "/"+getResources().getString(R.string.app_name));
myInput = new FileInputStream(databasePath);
Toast.makeText(this, "Backup Location " + directory, Toast.LENGTH_LONG).show();
} else if (item.equals("Restore")) {
myInput = new FileInputStream(directory.getAbsolutePath() + File.separator + "/"+getResources().getString(R.string.app_name));
myOutput = new FileOutputStream(databasePath);
Toast.makeText(this, "Backup Restored Successfully ", Toast.LENGTH_LONG).show();
}
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
} catch (Exception e) {
} finally {
try {
if (myOutput != null) {
myOutput.close();
myOutput = null;
}
if (myInput != null) {
myInput.close();
myInput = null;
}
} catch (Exception e) {
}
}
}
}
i want to copy file from asset to other application data directory.i have also given root acess to it.but this code doesn't work.its work on extenal storage directory .but not copy file in data directory..
public void onClick(View arg1){
String command[] = { "su", "-c", "ls", "/data" };
Shell shell = new Shell();
String text = shell.sendShellCommand(command);
if (new File((Object)Environment.getDataDirectory() + "/data/com.my/shared_pref/com.myxml").exists()) {
Toast.makeText(getApplicationContext(),"copied",Toast.LENGTH_LONG).show();
MainActivity.this.copyAssets();
}
else{
Toast.makeText(getApplicationContext(),"error! copy failed ",Toast.LENGTH_LONG).show();
private void copyAssets()
{
AssetManager assetManager = getAssets();
String[] files = null;
InputStream in = null;
OutputStream out = null;
String filename =
"com.my.xml" ;
try
{
in = assetManager.open( filename);
out = new FileOutputStream((Environment.getDataDirectory().toString() +"/data/com.my/shared_pref/" + filename));
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (IOException e)
{
Log. e ( "tag" , "Failed to copy asset file: " , e);
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
if anyone knows how to do it?
Pleaase suggest me.!!
Thanks.!!
This is exactly what you need. This code copies sample.apk from assets to the application data directory. You can change the path to anywhere you want.
private String copyAssets() {
AssetManager assetManager = getActivity().getAssets();
InputStream in = null;
OutputStream out = null;
String filename = "sample.apk";
String path = Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getActivity().getPackageName()
+ "/files";
try {
in = assetManager.open("files/" + filename);
File outFile = new File(path);
if (!outFile.exists()) {
outFile.mkdirs();
}
out = new FileOutputStream(outFile + "/" + filename);
copyFile(in, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return path + "/" + filename;
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
Use this code. I used this code in my project, Got it on net somewhare, it works.
private void copyDataBase() throws IOException
{
//Open your local db as the input stream
InputStream myInput = _context.getAssets().open(DB_NAME);
// Path to db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0)
{
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
I'm using Intent to export my .db file to the google drive. and import the .db file through the local folder on the device.
how can i import the file to my device from drive again?
what is the best way to "backup" the .db file and import the file?
it's possible to do that action without using "google drive api"?
Help me please !
public class BackUpDb {
Context context;
public BackUpDb(Context activity) {
this.context = activity;
}
public void exportDb(){
File direct = new File(Environment
.getExternalStorageDirectory()
+ "/folderToBeCreated");
if (!direct.exists()) {
if (direct.mkdir()) {
// directory is created;
}
}
try {
exportDB();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void importDb(){
importDB();
}
// importing database
#SuppressLint("SdCardPath")
private void importDB() {
try {
// File file = getBaseContext().getFileStreamPath(Environment.getExternalStorageDirectory()
// + "/MyDatabase");
// if(file.exists()){
FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory()
+ "/folderToBeCreated/MyDatabase");
String outFileName = "/data/data/com.example.application/databases/"+DbHandler.DB_NAME;
OutputStream output = new FileOutputStream(outFileName);
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(context, "Ok :)",Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(context, "No list found",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#SuppressLint("SdCardPath")
private void exportDB() throws IOException {
// Open your local db as the input stream
try {
String inFileName = "/data/data/com.example.application/databases/"+DbHandler.DB_NAME;
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+ "/folderToBeCreated/MyDatabase";
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
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();
} catch (Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG)
.show();
}
Toast.makeText(context,
"save to :\n/folderToBeCreated",Toast.LENGTH_LONG).show();
}
public void sendDb(String mailAddres){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("application/octet-stream");
intent.putExtra(Intent.EXTRA_EMAIL, new String[] {mailAddres});
intent.putExtra(Intent.EXTRA_SUBJECT, "MyDatabase");
File root = Environment.getExternalStorageDirectory();
File file = new File(root, "/folderToBeCreated/MyDatabase");
if (!file.exists() || !file.canRead()) {
Toast.makeText(context, "No sd-card", Toast.LENGTH_SHORT).show();
return;
}
Uri uri = Uri.parse("file://" + file.getAbsolutePath());
intent.putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(Intent.createChooser(intent, "BACKUP"));
}
}
Since, Android 4.4 (KitKat), the ability to create files on external SD cards has been removed.
Ive seen a few posts on how to import and export a database in android and i found these code, but i cant seem to make it work. I get the error java.io.filenotfoundexception /storage/sdcard0/BackupFolder/DatabaseName:open failed ENOENT (no such file or directory). Ive changed a few things but i still get no file found exception
here is my export:
private void exportDB() {
try {
db.open();
File newFile = new File("/sdcard/myexport");
InputStream input = new FileInputStream(
"/data/data/com.example.mycarfuel/data
bases/MyDatabase");
OutputStream output = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
db.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and my import:
private void importDB() {
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 dst = 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();
}
}
SQlite database to our local file system-
Function declaration-
try {
backupDatabase();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Function defined-
public static void backupDatabase() throws IOException {
//Open your local db as the input stream
String inFileName = "/data/data/com.myapp.main/databases/MYDB";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/MYDB";
//Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
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();
}
Above accepted answer will not work for Android version on or above 6 because database path is different.
please check below code . It will work on all devices.
public static boolean exportDB(Context context) {
String DATABASE_NAME = "my.db";
String databasePath = context.getDatabasePath(DATABASE_NAME).getPath();
String inFileName = databasePath;
try {
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory() + "/" + DATABASE_NAME;
OutputStream output = new FileOutputStream(outFileName);
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();
return true;
} catch (Exception e) {
return false;
}
}