Android: Issue in downloading to SD - java

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

Related

java The size of my programatically downloaded file is lesser than the file manually downloaded

I'm trying to programatically download a file from an api which the url has been provided, but the downloaded file always ended up incomplete, with a size lesser than the file I manually downloaded with the url...
This is my code :
try{
URL url = new URL(filesToBeDwlUrl);
HttpURLConnection c = (HttpURLConnection)url.openConnection();
c.setRequestMethod("GET");
c.connect();
//if connection response is not OK then log
if(c.getResponseCode() != HttpURLConnection.HTTP_OK){
Log.e("Response", "Server returned HTTP "+ c.getResponseCode());
}
storagePath = new File(mContext.getFilesDir().getAbsoluteFile() + "/"+ "AudiosArchiveFolder");
if(!storagePath.isDirectory())
storagePath.mkdir();
Log.v("Download-info ", "Directory created in internal storage : "+ storagePath);
outputZipFile = new File( storagePath, fileName);
FileOutputStream fos = new FileOutputStream(outputZipFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1;
while((len1 = is.read(buffer)) != -1){
fos.write(buffer, 0, len1);
}
fos.flush();
fos.close();
is.close();
}catch (Exception e){
mProgressDialog.dismiss();
outputZipFile = null;
Toast.makeText(mContext, "An error occurred. Multimedia content could not be saved on your device. Please contact customer support", Toast.LENGTH_SHORT).show();
Log.e("Download-error", "Error found: "+e.getMessage());
}
The url filesToBeDwlUrl value is : "http://play.digtransformations.com/api.custom.action.execute/YUBhLmFh/YWE=/81GQ/zbfd874/O8npdvQbJmexu8Hq/j8Hs";
I cannot yet figure out if the problem is with my code or if it is with the priovided url, since i can obtain the right zipped file when downloading manually the file.
Thanks for any help !
The problem is in getting the zip file from the site. Writing part in android is alright. When I tried to get the content type from URL, I get content type of 'text/html'. when I opened the downloaded file (.zip file) in notepad, I got a html page with all html code. The problem is from the website where the file is being written. In the website, the content-type should be properly maintained.

Android: Corrupted characters in PDF

I'm using HttpURLConnection to get a PDF file from the server then saving that PDF to the user's phone. Getting the file is working perfectly, but when saving, some files contain corrupted characters.
InputStream in = null;
OutputStream fileOutput = null;
try {
File file = new File(path);
file.mkdirs();
file = new File(path + File.separator + fileName + "." + fileExentsion);
file.createNewFile();
fileOutput = new FileOutputStream(file);
final byte[] buffer = new byte[1024];
int read;
in = conn.getInputStream();
while ((read = in.read(buffer)) != -1) {
fileOutput.write(buffer, 0, read);
}
fileOutput.flush();
return Uri.fromFile(file).toString(); // To open an intent in onPostExecute()
}
I tried using BufferedReader and BufferedWriter but the OS couldn't open the file after being saved. It is really weird because the same strings appears in other files correctly. And when downloading the file from a desktop, it looks good too.

I keep getting java.io.FileNotFoundException with my zip extractor

Could anybody help me with my java zip extractor as stated in the title I keep getting java.io.FileNotFoundException on the folders with files in them
public void UnZip() {
try {
byte[] data = new byte[1000];
int byteRead;
BufferedOutputStream bout = null;
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceFile)));
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
String filename = entry.getName();
File newfile = new File(Deobf2 + File.separator + filename);
System.out.println("file unzip : " + newfile.getAbsoluteFile());
new File(newfile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newfile);
int len;
while ((len = zin.read(data)) > 0) {
fos.write(data, 0, len);
}
fos.close();
entry = zin.getNextEntry();
}
zin.closeEntry();
zin.close();
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
error log
http://pastebin.com/crMKaa37
values
static String tempDir = System.getProperty("java.io.tmpdir");
public static File Deobf = new File(tempDir + "Deobf");
public static String Deobf2 = Deobf.toString();
entire code paste
http://pastebin.com/1vTfABR1
I have copy pasted same code and it is working fine. I think u dont have administrator permission on C drive. login As Administrator and run . it will work.
Access Denied Exception will come when u don have administrator level of permission on C drive.
The problem is Your doing
String Deobf2 = Deobf.toString();//this does not give the location of the file
use
file.getAbsolutePath();
in your case Deobf.getAbsolutePath();
instead. Check http://www.mkyong.com/java/how-to-get-the-filepath-of-a-file-in-java/
if you want to get the path only till the parent directory check this How to get absolute path of directory of a file?
Problem fixed changed some code
for anyone whos wants a copy of the working zip extraction code here you go http://pastebin.com/bXL8pUSg
The variable Deobf2 in the output of the zip

File not found exception - when creating new file on sdcard in android

In my application, my requirement is need to install .APK file from assets folder, so that I am trying to copy the apk file from assets folder to sdcard, I get File Not Found Exception.
these the following code:
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath();
String file_name = "ImageDownloading.apk";
AssetManager assetManager = getAssets();
try{
InputStream input = new BufferedInputStream(assetManager.open(file_name));
File path = new File(file_path);
if(!path.exists()){
path.mkdirs()
}
File file = new File(path,file_name);
OutputStream output = new FileOutputStream(file); // Here i get File Not Found Exception error.
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch(FileNotFoundException e){
Toast.makeText(MainActivity.this,"File not found exception " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
I have spent a lot of time but i did not find out the solution.
Do you have this permission set in your manifest file?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

SQLite Database from Internet

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.

Categories