I have been trying to export my database file into the external memory of my android phone by using
private final String DB_NAME = "MemberData";
private final String TABLE_NAME = "MemberDB";
//Get a reference to the database
File dbFile = this.getDatabasePath(DB_NAME);
//Get a reference to the directory location for the backup
File exportDir = new File(Environment.getExternalStorageDirectory(), "myAppBackups");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File backup = new File(exportDir, dbFile.getName());
//Check the required operation String command = params[0];
//Attempt file copy
try {
backup.createNewFile();
fileCopy(dbFile, backup);
} catch (IOException e) {
/*Handle File Error*/
}
private void fileCopy(File source, File dest) throws IOException {
FileChannel inChannel = new FileInputStream(source).getChannel();
FileChannel outChannel = new FileOutputStream(dest).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
}
It managed to create a directory name "myappsbackup" but my database couldnt be copied over. it is always size 0 and my tables are missing. Is there something wrong with my method of copying?
Here is the code I use to write or backup my SQLite db to the sdcard.
try {
db.open();
File newFile = new File("/sdcard/Your File Name Here");
InputStream input = new FileInputStream(
"/data/data/com.packageNameHere/databases/DB Name Here");
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();
}
Related
I am currently developing an application that reads,writes,updates,deletes json file.i have 4 json files namely data.json(to store name,address,area,pin),image.json(to store image name),location.json(to store latitute,longitude) and final.json that merges the above json files.final.json will combine all data from 3 files to make a single record.In a activity I need to read the name,date,time of all records stored in final.json in different radio buttons. I am unable to read only the name,date,time from a record stored in temp.json as temp.json contains latitute,longitude,image name,name,address,pin,area,date,time.Please help me do the following.Also I need to delete only specific record from temp.json file.
This is the code I used to read the text from temp.json.How to read only name,date,time from the file.I am able to read all the parameters
My temp.json looks like
{Record:["latitute":"22.456","longitude":"88.56","image_name":"xyz.jpg","name":"abc","address":"xx","area":""22","pin":"99","date":"03/05/2018" ,"time":"18:08:22"]} {Record:["latitute":"22.456","longitude":"88.56","image_name":"xyz.jpg","name":"abc","address":"xx","area":""22","pin":"99","date":"03/05/2018" ,"time":"18:08:22" ]}
String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
File myDir = new File(root + "/GeoPark");//create folder in internal storage
myDir.mkdirs();// make directory
File file = new File(myDir, FILENAME);//making a new file in the folder
if(file.exists()) // check if file exist
{
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Set the text
String x=text.toString();
String z=x.replace("{","").replace("date:","").replace("time:","").replace("Record:","").replace("[","").replace("latitude:","").replace("longitude:","").replace("name:","").replace("address:","").replace("pin:","").replace("area:","").replace("image:","").replace("\"","").replace("]","").replace("}","");
String[] y=z.split(",");
//rb1.setText(y[3].toString()+","+y[7].toString()+","+y[8].toString()+""+"");
// rb2.setText(y[11].toString()+","+y[15].toString()+","+y[16].toString());
//rb3.setText(y[19].toString()+","+y[23].toString()+","+y[24].toString());
//rb4.setText(y[27].toString()+","+y[31].toString()+","+y[32].toString());
}
else
{
rb1.setText("Sorry file doesn't exist!!");
}
///////merge code////
static class CopyFileContent {
public static void main(String[] args) {
JSONObject jsonObj2 = new JSONObject();
try {
// Here we convert Object to JSON
jsonObj2.put("date",a.toString());jsonObj2.put("time",c.toString());// Set the first name/pair
} catch (JSONException ex) {
ex.printStackTrace();
}
String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
File myDir = new File(root + "/GeoPark");//create folder in internal storage
myDir.mkdirs();// make directory
File destFile = new File(myDir, FILENAME11);//making a new file in the folder
/* Source file, from which content will be copied */
File sourceFile1 = new File(myDir,FILENAME12);
File sourceFile2 = new File(myDir,FILENAME13);
File sourceFile3 = new File(myDir,FILENAME14);
/* destination file, where the content to be pasted */
// File destFile = new File(FILENAME);
/* if file not exist then create one */
if (!destFile.exists()) {
try {
destFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream input1 = null;
InputStream input2 = null;
InputStream input3 = null;
OutputStream output = null;
InputStream input4=null;
try {
/* FileInputStream to read streams */
input1 = new FileInputStream(sourceFile1);
input2 = new FileInputStream(sourceFile2);
input3 = new FileInputStream(sourceFile3);
/* FileOutputStream to write streams */
output = new FileOutputStream(destFile,true);
byte[] buf = new byte[1024];
int bytesRead;
output.write("{Record:[".getBytes());
while ((bytesRead = input1.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f=new RandomAccessFile(destFile,"rw");
long length=f.length()-2;
f.setLength(length);
length=f.length();
f.close();
output.write(",".getBytes());
}
while ((bytesRead = input2.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f=new RandomAccessFile(destFile,"rw");
long length=f.length()-2;
f.setLength(length);
length=f.length();
f.close();
output.write(",".getBytes());
}
while ((bytesRead = input3.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f=new RandomAccessFile(destFile,"rw");
long length=f.length()-2;
f.setLength(length);
length=f.length();
f.close();
output.write(",".getBytes());
output.write(jsonObj2.toString().getBytes());
output.write("]}".getBytes());
output.write("\r\n".getBytes());
output.write("\r\n".getBytes());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (null != input1) {
input1.close();
}
if (null != input2) {
input2.close();
}
if (null != input3) {
input3.close();
}
if (null != output) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
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;
}
}
Context
I am copying a sqlite db file out of the assets to internal storage.
The file opens fine, but I wanted a additional layer of safety. There is
a slim possibility that when the file gets copied out it doesn't complete.
I decided to favor a check sum technique: specifically the MessageDigest
Java thing. so here's the code:
public ZipCode(Context ctx) {
this.ctx = ctx;
if (!databaseExist(ctx)) {
Log.d("ZipCode", "DB DNE");
inflate_db(ctx);
check_DB(ctx);
} else {
Log.d("ZipCode", "DB Exsits");
check_DB(ctx);
}
}
private static void inflate_db(Context ctx) {
byte[] buffer = new byte[2048];
int length;
AssetManager am = ctx.getAssets();
try {
BufferedInputStream is = new BufferedInputStream(
am.open(ZIPCODE_SQLITE_FAUX_FILE));
GZIPInputStream zis = new GZIPInputStream(is);
File dbfile = ctx.getDatabasePath(ZIPCODE_SQLITE);
FileOutputStream out = new FileOutputStream(dbfile);
while ((length = zis.read(buffer, 0, buffer.length)) > 0) {
out.write(buffer, 0, length);
}
out.flush();
out.close();
zis.close();
} catch (IOException e) {
e.printStackTrace();
Log.d("ERROR", e.getMessage());
}
}
private static void check_DB(Context ctx) {
File dbfile = ctx.getDatabasePath(ZIPCODE_SQLITE);
FileInputStream fis;
MessageDigest digester;
byte[] bytes = new byte[8192];
int byteCount;
try {
digester = MessageDigest.getInstance("MD5");
fis = new FileInputStream(dbfile);
while ((byteCount = fis.read(bytes)) > 0) {
digester.update(bytes, 0, byteCount);
}
String digest = Base64.encodeBytes(digester.digest());
Log.d("MD5 Sum", digest);
fis.close();
return;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
}
Now for the Question
Why is it that on fresh creation the check_DB's Log.d("MD5 Sum", digest);
has one output and say on relaunch (i.e. the DB file exists in internal storage)
the check_DB's Log.d("MD5 Sum", digest); has a different output.
Note:
databaseExist(ctx) checks for the DB file's existence per Android conventions.
private static boolean databaseExist(Context ctx) {
File dbFile = ctx.getDatabasePath(ZIPCODE_SQLITE);
return dbFile.exists();
}
why don't you calculate MD5 of your asset file (in your project directory) to find out which MD5 is right and which is wrong? then it'll be easier to find the problem part.
also, i'd suggest to replace (byteCount = fis.read(bytes)) > 0 with (byteCount = fis.read(bytes)) != -1 according to the FileInputStream reference manual.
When you use emulator your sqlite file is stored in a folder near your main application folder and you can download it. But this feature is not accessible in not rooted devices. How can I backup this existing sqlite file in SD Card programmatically?
I want to have a button in my application that stores this file in a special path in my SD Card. Is it possible?
Thanks,
You can try this, work for me, remember to get the WRITE_EXTERNAL_STORAGE permission in your manifest:
// Copy to sdcard for debug use
public static void copyDatabase(Context c, String DATABASE_NAME) {
String databasePath = c.getDatabasePath(DATABASE_NAME).getPath();
File f = new File(databasePath);
OutputStream myOutput = null;
InputStream myInput = null;
Log.d("testing", " testing db path " + databasePath);
Log.d("testing", " testing db exist " + f.exists());
if (f.exists()) {
try {
File directory = new File("/mnt/sdcard/DB_DEBUG");
if (!directory.exists())
directory.mkdir();
myOutput = new FileOutputStream(directory.getAbsolutePath()
+ "/" + DATABASE_NAME);
myInput = new FileInputStream(databasePath);
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) {
}
}
}
}
You can try following code,
String path = Environment.getExternalStorageDirectory().toString() + "/path";
File folder = new File( path );
if (!folder.exists())
{
folder.mkdirs();
}
File dbfile = new File( path + "/database.db" );
if ( !dbfile.exists() )
{
dbFile.createFile();
}
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
You can try this to copy a file:
public void copyFile(File in, File out) {
String DialogTitel = getString(R.string.daten_wait_titel);
String DialogText = getString(R.string.kopiervorgang_laeuft);
try {
// Dialogdefinition Prograssbar
final ProgressDialog dialog = new ProgressDialog(this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
dialog.setCancelable(false);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
dialog.show();
new Thread(new MyCopyThread(in, out)) {
#Override
public void run() {
try {
FileChannel inChannel = new FileInputStream(
MyCopyThread.in).getChannel();
FileChannel outChannel = new FileOutputStream(
MyCopyThread.out).getChannel();
try {
System.out.println("KOPIEREN");
inChannel.transferTo(0, inChannel.size(),
outChannel);
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
setCopyError(false);
} catch (IOException e) {
setCopyError(true);
// throw e;
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
dialog.dismiss();
// Abschlussarbeiten
if (useExternalSD == true) {
// Externe DB
moveDBtoExternFinish();
} else {
// Interne DB
moveDBtoInternFinish();
}
moveDBFinishHandler.sendMessage(moveDBFinishHandler
.obtainMessage());
} catch (Exception ex) {
}
}
}.start();
} catch (Exception exx) {
}
}
This is the code to get the filname of your internal db:
File interneDB = getApplicationContext().getDatabasePath(MY_DB_NAME);
Replace MY_DB_NAME with the name of your DB
I have an application to download zip file and save to sdcard. But I get zipentry=null while reading inputstream, it doesn't enter the while block. Could anyone help me in solving this problem, please?
try {
// fileInputStream = new InputStream(input);
ZipInputStream zipInputStream
= new ZipInputStream(new BufferedInputStream(input));
ZipEntry zipEntry=zipInputStream.getNextEntry();
Toast.makeText(getApplicationContext(), "I have entered try block zipentry"+zipEntry,Toast.LENGTH_LONG).show();
System.out.println("Zipentry is"+zipEntry);
while ((zipEntry = zipInputStream.getNextEntry()) != null){
Toast.makeText(getApplicationContext(), "Entered into while block",Toast.LENGTH_LONG).show();
String zipEntryName = zipEntry.getName();
File file = new File(to + zipEntryName);
if (file.exists()){
} else {
if(zipEntry.isDirectory()){
file.mkdirs();
}else{
byte buffer[] = new byte[BUFFER_SIZE];
FileOutputStream fileOutputStream = new FileOutputStream(file);
bufferedOutputStream
= new BufferedOutputStream(fileOutputStream, BUFFER_SIZE);
int count;
while ((count
= zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
bufferedOutputStream.write(buffer, 0, count);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
}
zipInputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "File not found",Toast.LENGTH_LONG).show();
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Input outout error",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
You already have one ZipEntry zipEntry=zipInputStream.getNextEntry(); before condition in the while loop. Leave it out and initialize it only in the while loop. Something like:
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null){
//
}