My problem is that my application always fails when the database is copied from asset folder to the phone path:
/data/data/at.atn.android/databases/
MY databasename:
atnRoutenplaner.sqlite3
My code for the transfer:
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
File sampleFile = new File(outFileName);
//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();
}
try this,
public void CopyDataBaseFromAsset() throws IOException{
InputStream in = ctx.getAssets().open("mycontacts");
Log.e("sample", "Starting copying" );
String outputFileName = DATABASE_PATH+DATABASE_NAME;
File databaseFile = new File( "/data/data/com.copy.copydatabasefromasset/databases");
// check if databases folder exists, if not create one and its subfolders
if (!databaseFile.exists()){
databaseFile.mkdir();
}
OutputStream out = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer))>0){
out.write(buffer,0,length);
}
Log.e("sample", "Completed" );
out.flush();
out.close();
in.close();
}
Related
I was previously storing a sqlite database in my apps assets folder but have now moved the database to external storage.
My previous copyDatabase() method looked like this.
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
OutputStream myOutput = new FileOutputStream(DB_PATH);
byte[] buffer = new byte[AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT];
while (true) {
int length = myInput.read(buffer);
if (length > 0) {
myOutput.write(buffer, 0, length);
} else {
myOutput.flush();
myOutput.close();
myInput.close();
return;
}
}
}
The issue is I'm unsure how to create an InputStream for opening the database from external storage. I can't seem to find the external storage equivalent to myContext.getAssets().open(DATABASE_NAME);
The current database path:
DB_PATH = Environment.getExternalStorageDirectory().getPath().toString()+"/SoulInfoDatabase/BB2SoulDatabase.db";
Step 1: Give storage permission in your App Manifesto file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step 2: Copy database to your custom SD card Path
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = context.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + "/" + DB_NAME;
// Open the empty db as the output stream
new File(outFileName).createNewFile();
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();
}
Step 3: Then Open your database:
try {
db = SQLiteDatabase.openDatabase(DB_PATH + "/" + DB_NAME, null,
SQLiteDatabase.OPEN_READWRITE
| SQLiteDatabase.NO_LOCALIZED_COLLATORS);
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
WHERE
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SoulInfoDatabase";
File file = new File(filePath);
if(!file.exists()){
file.mkdirs();
}
DB_PATH = filePath;
DB_NAME = "BB2SoulDatabase.sqlite";
Here is the code I am using (found in many answers):
InputStream myInput;
try {
myInput = iNezamApplication.getAppContext().getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
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 (IOException e1) {
e1.printStackTrace();
}
However, I always get an exception after reaching the OutpoutStream line:
java.io.FileNotFoundException: /data/data/package_name/databases/databasename.db: open failed: ENOENT (No such file or directory)
I tried something like this..
final String[] sample_dbName = {"DrugsNew.db"};
int assetDbSize = sample_dbName.length;
File databaseFile = new File( "/data/data/com.handyrep2.ui/databases");
// check if databases folder exists, if not create one and its subfolders
if (!databaseFile.exists()){
databaseFile.mkdir();
}
for(int i=0;i<assetDbSize;i++){
String outFilename =null;
outFilename = "/data/data/com.handyrep2.ui/databases"+ "/" + sample_dbName[i];
File sampleFile = new File(outFilename);
try {
InputStream in = activity.getAssets().open("offlinedb/"+sample_dbName[i]);
OutputStream out = new FileOutputStream(outFilename);
// Transfer bytes from the sample input file to the sample output file
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
// Close the streams
out.close();
in.close();
}catch(IOException e) {
}
}
Is "package_name" a substitute for your real package name just to post it here or do really use this in your DB_PATH? :)
you must create a File object at first
Currently, I am copying a database from my assets folder to the to the /data/data/package folder. This is that code (from the answer here), which works:
public void copyDataBase() throws IOException{
// open db as input stream
InputStream myInput;
//open empty db as output stream
OutputStream myOutPut;
try {
myInput = myContext.getAssets().open(DB_NAME);
//path to newly created db
String outFileName =DB_PATH + DB_NAME;
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);
}
myOutPut.flush();
myOutPut.close();
myInput.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Now in order to save space in the .apk download, I am trying to zip the file before copying it to the /data/data/package folder.
private void copyDataBaseFromZipFile() {
InputStream inputStream = null;
OutputStream outputStream = null;
String sourcePathname = this.getBundledPathname();
String destinationPath = this.getDatabasePathname();
try {
inputStream = this.mContext.getAssets().open(sourcePathname);
ZipInputStream zipStream = new ZipInputStream(inputStream);
int BUFFER = 8096;
outputStream = new FileOutputStream(destinationPath);
BufferedOutputStream dest = new BufferedOutputStream(outputStream, BUFFER);
ZipEntry entry;
while ((entry = zipStream.getNextEntry()) != null) {
if (entry.getName().equals("androidDB.sql")) }
int count;
byte data[] = new byte[BUFFER];
while ((count = zipStream.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
}
}
outputStream.flush();
outputStream.close();
dest.flush();
dest.close();
zipStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
When I attempt to open the database later (with SQLiteDatabse), I get this error: android.database.sqlite.SQLiteException: unable to open database file
I haven't changed anything except the file I'm copy from, which is only a zipped version of the one I was previously copying over. The final database is the right size, so it doesn't seem to be still compressed... If anyone has any suggestions or possible reasons WHY it won't open, it would be greatly appreciated.
You should remove these lines:
outputStream.flush();
outputStream.close();
Your BufferedOutputStream probably has some buffered bytes, but since you close outputStream before you call dest.flush(), those bytes are never actually written to the file.
How do I convert the following Android code to MonoAndroid code?
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty 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();
And are there any special dll references or using statements?
Thanks
After days of fiddling around and futile googling, 'Assets.Open(#"test.db")' was the key:
//Open your local db as the input stream
Stream myInput = Assets.Open(#"test.db");
string outFileName = Path.Combine(System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal), "test.db");
//Open the empty db as the output stream
Stream myOutput = new FileStream(outFileName,FileMode.OpenOrCreate);
byte[] buffer = new byte[1024];
int b = buffer.Length;
int length;
while ((length = myInput.Read(buffer,0,b))>0){
myOutput.Write(buffer, 0, length);
}
//Close the streams
myOutput.Flush();
myOutput.Close();
myInput.Close();
}
i have a file that i have stored in my assets folder. i read the file and attach certain data to the file as per the user requirement. i then store the file into my emulator into the data directory. i am using bufferedwriter for this purpose but it is not working and the resultant file made in the data folder has size 0kb. the file is being made.
here is my code
InputStream myInput = this.getAssets().open("exportformat.txt");
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(myInput));
String outFileName = "/data/data/packagename/attachment.txt";
OutputStream myOutput = new FileOutputStream(outFileName);
BufferedWriter outStream = new BufferedWriter(
new OutputStreamWriter(myOutput));
String datafromfile;
while ((datafromfile = inputStream.readLine()) != null) {
StringBuffer sb = new StringBuffer(datafromfile);
if (datafromfile.equals("DTSTART:"))
sb.append(details[2]);
if (datafromfile.equals("DTEND:"))
sb.append(details[3]);
if (datafromfile.equals("SUMMARY:"))
sb.append(details[0]);
if (datafromfile.equals("DESCRIPTION:"))
sb.append(details[1]);
datafromfile = sb.toString();
outStream.write(datafromfile);
outStream.newLine();
}
// Close the streams
myOutput.flush();
myOutput.close();
outStream.close();
inputStream.close();
myInput.close();
} catch (Exception e) {
e.printStackTrace();
}
}
i have tried debugging. the data is being correctly read , it is only the write operation that is not working.
thank you in advance.
ANSWER:
the following code is working:
InputStream myInput = this.getAssets().open("exportformat.txt");
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(myInput));
String outFileName = "/data/data/com.helios.NauticDates/attachment.ics";
File checkfile = new File(outFileName);
if(checkfile.exists()){
checkfile.delete();
}
for(int i =0 ;i<4;i++){
if(details[i].equals("null"))
details[i]=" ";
}
FileOutputStream myOutput = new FileOutputStream(outFileName);
String datafromfile;
while ((datafromfile = inputStream.readLine()) != null) {
StringBuffer sb = new StringBuffer(datafromfile);
if (datafromfile.equals("DTSTART:"))
sb.append(details[2]);
if (datafromfile.equals("DTEND:"))
sb.append(details[3]);
if (datafromfile.equals("SUMMARY:"))
sb.append(details[0]);
if (datafromfile.equals("DESCRIPTION:"))
sb.append(details[1]);
if(datafromfile.equals("CATEGORIES:"))
sb.append(details[4]);
datafromfile = sb.toString();
datafromfile+="\n";
byte[] temp = datafromfile.getBytes();
myOutput.write(temp);
}
// Close the streams
myOutput.flush();
myOutput.close();
inputStream.close();
emailintent.putExtra(Intent.EXTRA_STREAM,Uri.parse(outFileName));
emailintent.setType("plain/text");
startActivity(Intent.createChooser(emailintent, "Send mail..."));
} catch (Exception e) {
e.printStackTrace();
}
Try using a FileWriter instead of a FileOutputStream like so:
FileWriter myOutput = new FileWriter(outFileName);
BufferedWriter outStream = new BufferedWriter(myOutput);
I have a code in which I am copying sqlite database from assets folder to the android system's data folder.
private String DB_PATH =mycontext.getPackageName() + "/databases/";
private static String DB_NAME = "PartyDetails.sqlite";
private void copydatabase() throws IOException {
//Open your local db as the input stream
InputStream myinput = mycontext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outfilename = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myoutput = new FileOutputStream(outfilename);
// transfer byte to inputfile to 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();
}
Hope it helps :-)