SQLite Database from Internet - java

I have a rather large database that ships with my app. I'm having a lot of trouble getting it to properly create itself on the local device, so I figure with the issues and it being so large, it might make more sense to host it on a server and work with it from there.
The database is 40 MB or less. What is the best way to manage this with it hosted somewhere?

The problem is with Database file size. You can make a Zip of your Database file and then copy it to your local path from Assets.
Here is the link: Copy Db File From Assets
Now, in that code replace the copyDataBase() function with the below one.
private void copyDataBase() throws IOException {
try {
InputStream mInputStream = mContext.getAssets().open(DB_NAME_ZIP);
String outFileName = DB_PATH + DB_NAME_ZIP;
OutputStream mOutputStream = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = mInputStream.read(buffer)) > 0) {
mOutputStream.write(buffer, 0, length);
}
ZipFile mZipFile = new ZipFile(DB_PATH + DB_NAME_ZIP);
InputStream nInputStream = mZipFile.getInputStream(mZipFile.getEntry(DB_NAME));
OutputStream nOutputStream = new FileOutputStream(DB_PATH + DB_NAME);
while ((length = nInputStream.read(buffer)) > 0) {
nOutputStream.write(buffer, 0, length);
}
nOutputStream.flush();
nOutputStream.close();
nInputStream.close();
// Close the streams
mOutputStream.flush();
mOutputStream.close();
mInputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
//Delete Zip file to minimize memory usage
final String mPath = DB_PATH + DB_NAME_ZIP;
final File file = new File(mPath);
if (file.exists())
file.delete();
}
}
Here DB_NAME_ZIP is the Database Zip file what you put in Assets folder like Android.zip but it actually contains Android.sqlite or Android.db.
I hope this one can help you.

Related

android copy mp3 file success but duration not change

i try to copy mp3 file in external storage and limit duration of new file. it work but when it started, although i run to limit time, it still display end time like old file.
private void copy(File in, File out) throws IOException {
FileInputStream is = null;
FileOutputStream os = null;
try {
is = new FileInputStream(in);
os = new FileOutputStream(out);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0 && out.length()<175642) {
os.write(buffer, 0, length);
}
} finally {
assert is != null;
is.close();
assert os != null;
os.close();
}
}
how can i fix it. i really expect your help. have a nice day,everyone!
You simply cut of the rest of the file. This leads to a kind of corrupted file because the data in the header-block (e.g. the length) is no longer correct.
For some information about the mp3 file format:
https://en.wikipedia.org/wiki/MP3
I highly recommend to adjust the header information after shortening the file.

Java copy files from source zip to destination zip on Oracle database

Have a Word DOCX file stored in a table (zip file). With Java stored procedure, I like to replace some string inside "word/document.xml" file and store all files into new archive. If I run the code on Oracle database I get corrupted zip file. File size of ouptut file is smaller than input file...
If I run the same app on client (Netbeans IDE) then all works fine. I can't find the where is the problem!?
public static void zamenjajVsebino(oracle.sql.BLOB srcBlob1, oracle.sql.BLOB[] dstBlob) throws Exception {
InputStream zipBuffer = srcBlob1.getBinaryStream();
OutputStream outBuffer = dstBlob[0].getBinaryOutputStream();
ZipInputStream zipIn = new ZipInputStream(zipBuffer);
ZipOutputStream zipOut = new ZipOutputStream(outBuffer);
ZipEntry inEntry;
while ((inEntry = zipIn.getNextEntry()) != null) {
ZipEntry outEntry = new ZipEntry(inEntry.getName());
zipOut.putNextEntry(outEntry);
if (inEntry.getName().equals("content.xml") | inEntry.getName().equals("word/document.xml")) {
String contentIn = new String(getStringByte(zipIn), "UTF-8");
contentIn = contentIn.replaceAll("%TEXT%", "BLA BLA");
zipOut.write(contentIn.getBytes(), 0, contentIn.getBytes().length);
} else {
copy(zipIn, zipOut);
}
zipOut.closeEntry();
}
zipIn.close();
zipOut.flush();
zipOut.finish();
}
public static void copy(InputStream in, OutputStream out) throws IOException {
int n;
byte[] buffer = new byte[1024];
while ((n = in.read(buffer)) > -1) {
out.write(buffer, 0, n); // Don't allow any extra bytes to creep in, final write
}
out.flush();
}
If I open the source DOCX file is like this:
The output file is like this:
Here is my plsql source code:
-- select source docx file from blob...
select vdb.vsebina
into SrcBlobLocator
from dok_vsebina_dokumenta_blob vdb
where id=p_vdb_id;
-- prepare output blob
p_vdb_id_out:=dok_lob.f_pripravi_blob;
update dok_vsebina_dokumenta_blob set
naziv_datoteke='test.docx',
vsebina = empty_blob()
where id=p_vdb_id_out;
--select output blob for update...
select vdb.vsebina
into DstBlobLocator
from dok_vsebina_dokumenta_blob vdb
where id=p_vdb_id_out for update;
-- call java stored procedure with source and dest blob...
ZamenjajVsebino(SrcBlobLocator, DstBlobLocator);

Unzipped DB in Android not readable

I am trying to transfer a SQLite database into an app by downloading it and then unzipping it to the correct location. I was successful in transferring the DB when it was unzipped. The error I get is that it cannot find any of the tables I query. I have also been successful in unzipping and reading normal text files.
The DB has Hebrew and English, but that has not caused problems before. The bilingual DB was copied successfully when it was not zipped and bilingual texts have been successfully unzipped and read. Still, it is a possibility that there is an encoding problem going on. That seems weird to me, because as you can see below in the code, I'm just copying the bytes directly.
-EDIT-
Let's say the prezipped db is called test1.db. I zipped it, put it in the app, unzipped it and called that test2.db. when I ran a diff command on these two, there were no differences. So there must be a technical issue with the way android is reading the file / or maybe encoding issue on android that doesn't exist on pc?
I hate to do a code dump, but i will post both my copyDatabase() function (which works). That is what I used previously running it on an unzipped DB file. I put it here as comparison. Now I'm trying to use unzipDatabase() function (which doesn't work), and use it on a zipped DB file. The latter function was copied from How to unzip files programmatically in Android?
private void copyDatabase() throws IOException{
String DB_NAME = "test.db";
String DB_PATH = "/data/data/org.myapp.myappname/databases/";
//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();
}
private boolean unzipDatabase(String path)
{
String DB_NAME = "test.zip";
InputStream is;
ZipInputStream zis;
try
{
String filename;
is = myContext.getAssets().open(DB_NAME);
zis = new ZipInputStream(is);
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null)
{
// write to a file
filename = ze.getName();
// Need to create directories if not exists, or
// it will generate an Exception...
if (ze.isDirectory()) {
Log.d("yo",path + filename);
File fmd = new File(path + filename);
fmd.mkdirs();
continue;
}
OutputStream fout = new FileOutputStream(path + filename);
// reading and writing zip
while ((count = zis.read(buffer)) != -1)
{
fout.write(buffer, 0, count);
}
fout.flush();
fout.close();
zis.closeEntry();
}
zis.close();
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
So still don't know why, but the problem is solved if I first delete the old copy of the database (located at DB_PATH + DB_NAME) and then unzip the new one there. I didn't need to do this when copying it directly.
so yay, it was a file overwriting issue...If someone knows why, feel free to comment

Android: Issue in downloading to SD

I've developed an application in which user can download .mp3 files from server. And pre-defined a path to mnt/sdcard/foldername for saving such files. I had run my program in HTC, LG, Samsung works perfect but when I running a same program at samsung galaxy s2 getting an issue that can't able to write(store) in mnt/sdcard/foldername and tried
Environment.getExternalStorageDirectory().getAbsolutePath()
but its shows downloaded file names in given path and zero bytes for each files properties. Any idea to solve this issue?
The SG2 does usually not have a sd-card and uses the internal flash memory as "external" storage. I have solved this issue with this code:
private File initCacheDir() {
String sdState = android.os.Environment.getExternalStorageState();
File imageCacheDir;
if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
File sdDir = android.os.Environment.getExternalStorageDirectory();
imageCacheDir = new File(sdDir, "Android/data/" + App.PACKAGE_NAME + "/files/imageCache");
}
else
imageCacheDir = context.getCacheDir();
if(!imageCacheDir.exists())
imageCacheDir.mkdirs();
return imageCacheDir;
}
Note that this code give you the location of the cache directory, which is usually located in the Android/data folder on the sd-card.
You'll find more details how to solve this issue with SG2 here:
How could i get the correct external storage on Samsung and all other devices?
try this
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"yourfile");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
I finally found the code
public void download(String urlToDownload){
URLConnection urlConnection = null;
try{
URL url = new URL(urlToDownload);
//Opening connection of currrent url
urlConnection = url.openConnection();
urlConnection.connect();
//int lenghtOfFile = urlConnection.getContentLength();
String PATH = Environment.getExternalStorageDirectory() + "/1/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "file.mp3");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = url.openStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
System.out.println("downloaded"+urlToDownload);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Source: link

Moving database on Android

I am shipping my Android application with an SQLite database (300 KB), and after what I read I need to move it in order to use it. In iOS you move the database from the app to the documents folder because you can't write to the app because it is signed. Is this the reason on Android as well? So back to my question. The following code does not copy the database correctly, it only copies some of it. Why so? Have I done something wrong here.
private final static String DB_NAME = "klb.sqlite";
dbPath = "/data/data/" + context.getPackageName() + "/databases/"; // setting this in constructor
(The lines above is private members, applies to both code examples below)
BufferedInputStream bis = new BufferedInputStream(context.getAssets().open(DB_NAME));
FileOutputStream fos = new FileOutputStream(dbPath + DB_NAME);
while (bis.read() != -1) {
fos.write(bis.read());
}
bis.close();
fos.flush();
fos.close();
However this works: (Sorry for being lazy about re-indenting)
InputStream inputStream = context.getAssets().open("klb.sqlite");
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
while (bis.read() != -1) {
fos.write(bis.read());
}
Look at that closely. Your calling read twice, but write once. You're effectively skipping every other byte.

Categories