Display image from sd card (Android 2.3 vs 4.0.4) - android

I'm downloading an Image using this code:
// Download AVATAR
try {
File avatar = new File(Environment.getExternalStorageDirectory() + "/Android/data/carl.fri.fer.omegan/avatar.jpg");
prefs.edit().putString("loginUser", json.name).commit();
prefs.edit().putInt("loginMatter", json.darkmatter).commit();
if (!avatar.exists()) {
Log.i("AVATAR", "Downloading user avatar...");
URL url = new URL("Valid URL");
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(avatar);
fos.write(baf.toByteArray());
fos.close();
}
else Log.i("AVATAR", "The user avatar already exists!");
} catch (IOException e) { System.out.println("Error downloading avatar: " + e); }
And then I try to show this image using this code:
File usrAvatar = new File(Environment.getExternalStorageDirectory() + "/Android/data/carl.fri.fer.omegan/avatar.jpg");
if(usrAvatar.exists()) {
Bitmap avatarBmp = BitmapFactory.decodeFile(usrAvatar.getAbsolutePath());
userAvatar.setImageBitmap(avatarBmp);
}
The problem appears here:
userAvatar.setImageBitmap(avatarBmp);
Android 4.0.4: Error type: NullPointerException.
Android 2.3.5: Error type: ImageView not showing image but no error appears.
1- The ImageView userAvatar is right because I can show and image from the drawable folder.
2- The image I want to show is downloaded successfully because using a file manager I can find it on the specified folder and file name.
3- The image is not corrupted because I can open it using any image viewer.
So, which can be the problem? It's driving be crazy!
Any help will be appreciated.
Thank you in advantatge!

try the following code:
ImageView bmImage;
FileInputStream instream = new FileInputStream("/sdcard/Pictures/Image.png");
BufferedInputStream bif = new BufferedInputStream(instream);
byteImage1 = new byte[bif.available()];
bif.read(byteImage1);
textView.append("\r\n" + byteImage1+"\r\n");
bmImage.setImageBitmap(BitmapFactory.decodeByteArray(byteImage1, 0, byteImage1.length));
textView.append("\r\n" + byteImage2+"\r\n");

Related

Downloading and saving images from https URLs in android

I have this function that downloads and saves images in device -
public void DownloadFromUrl(String WebURL, String fileName) {
try {
URL url = new URL(WebURL);
file = new File(context.getFilesDir() + fileName+".jpg");
long startTime = System.currentTimeMillis();
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
If I supply an https URL, it cannot save the image. Any pointers on how to download and save https images ?
I hope this link will help you. Uploading/Downloading Pictures by Tonikami.
https://www.youtube.com/playlist?list=PLe60o7ed8E-Q7tqKNPnWFdUoeniqH_-A9
Just use Picasso or Glide. It is super easy to use. And the best part is that it does automatic disk and memory caching, so you do not have to worry about anything.
Picasso - check out this link.
OR
Glide - check out this link.
The only mistake I made above is that I was trying to download and save large images when connectivity was slow. Some of my images are around 5-10 MB. Otherwise the code is fine.

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);
}
}

how can i download audio file from server by url

how can i download audio file from server by url and save it to sdcard.
i am using the code below:
public void uploadPithyFromServer(String imageURL, String fileName) {
try {
URL url = new URL(GlobalConfig.AppUrl + imageURL);
File file = new File(fileName);
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 1024 * 50);
FileOutputStream fos = new FileOutputStream("/sdcard/" + file);
byte[] buffer = new byte[1024 * 50];
int current = 0;
while ((current = bis.read(buffer)) != -1) {
fos.write(buffer, 0, current);
}
fos.flush();
fos.close();
bis.close();
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
the above code is not downloading audio file.
if use any permission in menifest file plz tell me.. (i have used internet permission)
please help
thanks..
you must also add
android.permission.WRITE_EXTERNAL_STORAGE
permission if you wish to write data to sd card.
also post your logcat output , if you are getting any IOExceptions.
Your example does not specify a request method and some mimetypes and stuff.
Here you will find a list of mimetypes http://www.webmaster-toolkit.com/mime-types.shtml
Find the mimetypes relevant to you and add it to the mimetypes specified below in the code.
Oh and btw, the below is normal Java code. You'll have to replace the bit that stores the file on the sdcard. dont have an emulator or phone to test that part at the moment
Also see the docs for storage permissions on sd here: http://developer.android.com/reference/android/Manifest.permission_group.html#STORAGE
public static void downloadFile(String hostUrl, String filename)
{
try {
File file = new File(filename);
URL server = new URL(hostUrl + file.getName());
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.addRequestProperty("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-shockwave-flash, */*");
connection.addRequestProperty("Accept-Language", "en-us,zh-cn;q=0.5");
connection.addRequestProperty("Accept-Encoding", "gzip, deflate");
connection.connect();
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream("c:/temp/" + file.getName());
byte[] buffer = new byte[1024];
int byteReaded = is.read(buffer);
while(byteReaded != -1)
{
os.write(buffer,0,byteReaded);
byteReaded = is.read(buffer);
}
os.close();
} catch (IOException e) {
e.printStackTrace();
}
Then call,
downloadFile("http://localhost/images/bullets/", "bullet_green.gif" );
EDIT:
Bad coder me.
Wrap that input InputStream in a BufferedInputStream. No need to specify buffersizes ect.
Defaults are good.

how to use an image stored in internal data storage in android

In my app when the splash screen gets started I am downloading an image from the URL. I want to use the same image in another activity of my app. Following is my code to download the image
public void DownloadImage(String fileName)
{
try
{
URL url = new URL(main.BannerImage); //you can write here any link
File file = new File(fileName);
Log.e("file ",""+file);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
catch (IOException e)
{
Log.e("Error: ","" + e);
}
How can I get the image as a background source in another activity please help me friends
You can save the image in SDCard and the path can be send to next activity using
intent.putExtras("filename","filepathname");
and get in the next activity using
getIntent().getExtras().getString("filename")
from this you can get filepath from previous activity and you can get the image from specific filepath.
You can convert the image into bitmap and and pass it to next activity using Parcelable like
Bundle extras = new Bundle();
extras.putParcelable("data",bitmap);
Intent intent=new Intent(currentActivity.this,nextImage.class);
intent.putExtras(extras);
startActivity(intent);
finish();
in nextactivity you can get bitmap as
Bitmap image=getIntent().getExtras().getParcelable("data");

Getting error when I try to download file

I found this source code on the net and have modified it a little. But I get an error saying: java.io.FileNotFoundException /data/datafile.zip.
What should I do to get it running? Do I have to create the file first?
Thanks, Sigurd
private Thread checkUpdate = new Thread() {
public void run() {
try {
long startTime = System.currentTimeMillis();
Log.d("Zip Download", "Start download");
File file = new File(Environment.getDataDirectory(), "datafil.zip");
Log.d("Zip Download", file.getAbsolutePath());
URL updateURL = new URL("http://dummy.no/bilder/bilder/XML_Item_Expo_01.zip");
URLConnection conn = updateURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
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.close();
Log.d("Zip Download", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
} catch (Exception e) {
Log.d("Zip Download", "Error: " + e);
}
}
};
Seems like permission error. You maybe writing to the wrong place. Check that answer at link below,
Data directory has no read/write permission in Android
Environment.getDataDirectory() does not return a path where you can place files. You should use one of these methods instead:
Environment.getExternalStorageDirectory() gives you a path to external storage (SD card).
getFilesDir() from an Activity or other Context. Gives a path to app's internal file storage
You can also call openFileOutput() with a string file name (no path, just the file), which will open the FileOutputStream and create the file all in one shot for your use.
Hope that Helps!

Categories

Resources