Save & retrieve images from SQLite database - android

I'm trying to save the path of a downloaded file that was saved to the SD card, but I'm running into troubles when I try to retrieve it. When I try to convert it to a Bitmap, it says the file can't be found, even though it is on the SD card.
File example : /storage/emulated/0/_1404876264453.jpeg
Here's the code that I use to download a photo, and store it to the SD card (returns the URL of where it is saved on the device):
private String downloadProfile(String url)
{
String imageUrl = null;
try
{
String PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
String mimeType = getMimeType(url);
String fileExtension = "."+mimeType.replace("image/", "");
URL u = new URL(url);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.connect();
long millis=System.currentTimeMillis();
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "_"+millis);
FileOutputStream f = new FileOutputStream(outputFile);
InputStream in = con.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read()) > 0){
f.write(buffer, 0, len1);
}
imageUrl = outputFile.getAbsolutePath()+fileExtension;
f.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return imageUrl;
}
After downloading it, I insert the above URL into a SQLite database; it stores fine. I used Astro file manager to check if the file was there, and it was.
Here's the code in my BaseAdapter that takes the above file url and attemps to convert it into a Bitmap:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
String profilePath = result_pos.get("profile_url"); // this just returns the example url
Bitmap bitmap = BitmapFactory.decodeFile(profilePath, options);
imageView.setImageBitmap(bitmap);
LogCat:
07-08 23:35:17.660: E/BitmapFactory(25463): Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/_1404876264453.jpeg: open failed: ENOENT (No such file or directory)

check this link.i hope its useful to you.
reference link
1)create your own folder and save image name in proper way.
2)save image path in sqlite database
3)retrieve same path for get images.

Related

Files downloaded with donwloadManager disappears

I have an app that downloads about 6k photos from a server and store them in a folder configured y my app settings, I keep the files hidden from the gallery with .nomedia file and they are only visible in my app gallery, but when I leave my device charging about 5000 photos disappears, and there are only about 920 left in the folder, I totally don't know why files are being deleted.
here is my download file code
DownloadManager downloadManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request;
fileURL = convertUri(fileURL);
if (!URLUtil.isValidUrl(fileURL)) { return false; }
Uri downloadUri = Uri.parse(fileURL);
String fileName = URLUtil.guessFileName(fileURL, null, MimeTypeMap.getFileExtensionFromUrl(fileURL));
deleteFileIfExists( new File( getAbsolutePath(path), fileName ));
request = new DownloadManager.Request(downloadUri);
request.setAllowedNetworkTypes( DownloadManager.Request.NETWORK_WIFI )
.setTitle(fileName)
.setAllowedOverRoaming(false)
.setVisibleInDownloadsUi(false)
.setDestinationInExternalPublicDir( getPath(path), fileName );
downloadManager.enqueue(request);
Add System.currenttimeMillisecond() to fileUrl to make sure that your file name not to be duplicate .
This weekend i tested with 3 different devices and 2 different download methods, in the one with download manager the files dissapeared, so if someone have the same problem here's how I am donwloading the files:
public static boolean downloadFile(Activity activity, String fileURL) {
fileURL = convertUri(fileURL);
if (!URLUtil.isValidUrl(fileURL)) { return false; }
try {
String fileName = URLUtil.guessFileName(fileURL, null, MimeTypeMap.getFileExtensionFromUrl(fileURL));
deleteFileIfExists( new File( activity.getExternalFilesDir(""), fileName ));
URL u = new URL(fileURL);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
File file = new File(activity.getExternalFilesDir(""), fileName);
DataOutputStream fos = new DataOutputStream(new FileOutputStream(file));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return false; // swallow a 404
} catch (IOException e) {
return false; // swallow a 404
}
return true;
}

Get files from web service

I have a URL(http://xxx.xxx/api/getFiles) which is returning a JSON response. According to the developer of the API, this link also return files (images, pdf, word, excel, video, etc) that we're going to download to our Android device.
This link returns a file path (e.g. "/File Folder/") and file name (e.g. "Penguins.jpg") that will be used to link the file to the web server but I don't have an idea how to do it.
Are there ways to download it using this API?
JSON response:
{
   "status":"success",
   "count":1,
   "files":[
      {
         "file_code":"2",
         "file_name":"Penguins.jpg",
         "file_type":".jpg",
         "file_path”:”\/File Folder\/“
      }
   ]
}
To download file from url following peice of code can help you:
This code will create connection with url server and download it to specified path:
int downloadedSize = 0;
int totalSize = 0;
try {
URL url = new URL("download file url");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
//set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the downloaded file
File file = new File(SDCardRoot, "DownloadFileNameWithExtension"); // like test.png
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
//close the output stream when complete //
fileOutput.close();
} catch (final MalformedURLException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
} catch (final Exception e) {
e.printStackTrace();
}
Don't forget to add Internet permission in your manifest:D

I can't access a video after download it in android

I have a code to download a video from my server and save it in the sd card. I use this code:
String videoURL = "http://www.myapp.com" + key + "/"+key+".avi";
String PATHSdcard = getSDFile();
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL(videoURL);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(PATHSdcard,key+".avi");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
}
//close the output stream when done
fileOutput.flush();
fileOutput.close();
sendBroadcast (
new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory()))
);
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I download it correctly, but I can't play the video after downloaded it.
If I close my application and open again, the video works fine. Any solution?
Thanks in advance
Ensure you have the correct permissions to write to the file. In your manifest file, include this line
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />.
UPDATED:
I am not sure what problem in your code, but can you try my code, maybe it will work:
public void DownloadFromUrl(String DownloadUrl, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/your_downloads");
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); //you can write here any link
File file = new File(dir, fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
}

Can't save images from URL. Android

first, sorry for my bad english and second, I have a "little" problem.
I tested a lot of codes from StackOverFlow but i continue with the same problem.
I'm trying to download some images from URL. I have an ExpandableListView and I use a class named Downloadusers to download all information about users.
In this class I get the user's photo URL and I download the images with the following code:
private void downloadFile(String url) {
String filepath = null;
try
{
URL nurl = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) nurl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = getExternalFilesDir(null);
String filename = url.substring(url.lastIndexOf('/') + 1);
Log.i("Local filename:",""+filename+" SDCardRoot: "+SDCardRoot.toString());
File file = new File(SDCardRoot,filename);
if(file.createNewFile())
{
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[PHOTO_FILE_MAX_SIZE];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fileOutput.close();
if(downloadedSize==totalSize) filepath=file.getPath();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
filepath=null;
e.printStackTrace();
}
Log.i("filepath:"," "+filepath);
}
I have also verified that the URLs are correct and I have loaded in the browser.
With Log.i("filepath:"," "+filepath); I can see that filepath is correct, so I think that images are downloaded correctly but no, image files are corrupt files, so when I go to load the images into my ImageView I have a NullPointException because bMap readed is null due to corrupt images.
I have all permissions: Internet, Write and read external storage and phone state.
I tried too download images with AsyncTask, but I have the same problem.
Someone know what can be my problem?
Thanks.
Here it is my download method. You will download image into SDCARD. You can check whether image is downloaded or not by going DDMS Perspective.
public void download(String Url) throws IOException {
URL url = new URL (Url);
InputStream input = url.openStream();
try {
File storagePath = new File(Environment.getExternalStorageDirectory());
OutputStream output = new FileOutputStream (new File(storagePath, 'myImage.jpg'));
try {
byte[] buffer = new byte[2048];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
}
This snippet is for showing downloaded image in ImageView.
ImageView image = (ImageView) findViewById(R.id.image);
Bitmap bitmap = BitmapFactory.decodeFile(Environment
.getExternalStorageDirectory() + "myImage.jpg");
image.setImageBitmap(bitmap);
I solved my problem using library nostra13 "universal-image-loader-1.9.2.jar". My code is now:
// If the user photo exists and is public, download and show it.
if (Utils.connectionAvailable(activity)
&& (photoFileName != null) && !photoFileName.equals("")
&& !photoFileName.equals(Constants.NULL_VALUE)) {
// Create options. Setting caché = true (default = false)
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.build();
// Create global configuration and initialize ImageLoader
// with this configuration
ImageLoaderConfiguration config = new ImageLoaderConfiguration
.Builder(activity.getApplicationContext())
.defaultDisplayImageOptions(options)
.build();
ImageLoader.getInstance().init(config);
// Load image, decode it to Bitmap and display Bitmap in ImageView
// (or any other view
// which implements ImageAware interface)
ImageLoader.getInstance().displayImage(photoFileName, image);
}
With that code I can load the image on caché and show in my imageview without problems.
Thanks to all.
I had the same problem, but I was able to solve it by setting
urlConnection.setDoOutput(false);
and it worked, but I don't know why.

BitmapFactory returns null

I am working on an application where I am getting an image from the web server.
I need to save that image in a sqlite database. Maybe it will be saved in a byte[]; I have done this way, taking the datatype as blob, and then retrieving the image from db and showing at imageview.
I am stuck somewhere, however: I am getting null when I decodefrom bytearray
The code I have used is:
InputStream is = null;
try {
URL url = null;
url = new URL(http://....);
URLConnection ucon = null;
ucon = url.openConnection();
is = ucon.getInputStream();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer barb = new ByteArrayBuffer(128);
int current = 0;
try {
while ((current = bis.read()) != -1) {
barb.append((byte) current);
} catch (IOException e) {
e.printStackTrace();
}
byte[] imageData = barb.toByteArray();
Then I have inserted imageData in to the db..
To retrieve the image:
byte[] logo = c.getBlob(c.getColumnIndex("Logo_Image"));
Bitmap bitmap = BitmapFactory.decodeByteArray(logo, 0, logo.length);
img.setImageBitmap(bitmap);
But I am getting the error:
Bitmap bitmap is getting null.
Sometimes, It happens, when your byte[] not decode properly after retrieving from database as blob type.
So, You can do like this way, Encode - Decode,
Encode the image before writing to the database:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, THUMB_QUALITY, outputStream);
mByteArray = outputStream.toByteArray(); // write this to database as blob
And then decode it like the from Cursor:
ByteArrayInputStream inputStream = new ByteArrayInputStream(cursor.getBlob(columnIndex));
Bitmap mBitmap = BitmapFactory.decodeStream(inputStream);
Also, If this not work in your case, then I suggest you to go on feasible way..
Make a directory on external / internal storage for your application
images.
Now store images on that directory.
And store the path of those image files in your database. So you
don't have a problem on encoding-decoding of images.

Categories

Resources