How should I load an image from http using a Thread in android?
I would like to show the layout while waiting the image to load.
Now I'm using this code to show my img from http, and it show a dark blank screen for a few time before show the result:
private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
Can anyone help me?
Use this for load images from http
ImageView img_item;
String image_url = "here url"
new Thread(new Runnable()
{
public void run()
{
try
{
final Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(image_url).getContent());
img_item.post(new Runnable()
{
public void run()
{
if(bitmap !=null)
{
img_item.setImageBitmap(bitmap);
}
}
});
} catch (Exception e)
{
// TODO: handle exception
}
}
}).start();
you should pass your ImageView object to your method. and method run as a thread.
Related
I'm trying to use WallpaperManager in a ViewPager. I've got a button which is supposed to set the current image in the ViewPager to wallpaper. My problem comes with the line of code wallpManager.setResource(newInt);... the integer it comes up with is always 0 (zero), and so the app crashes and LogCat says there's no Resource at ID #0x0. As a test to see if I'm getting the correct image URL I've done this:
String newStr = images[position];
CharSequence cs = newStr;
Toast.makeText(UILPager.this, cs, Toast.LENGTH_SHORT).show();
And the resulting Toast shows the correct image URL. I can't figure out how to convert the URL which is in the form of "http://www.example.com/image.jpg" to an Integer so that the WallpaperManager can use it. Here's what the whole button code looks like:
wallp_BTN.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
WallpaperManager wallpManager = WallpaperManager.getInstance(getApplicationContext());
String newStr = images[position];
int newInt = 0;
try{
newInt = Integer.parseInt(newStr);
} catch(NumberFormatException nfe) {
}
CharSequence cs = newStr;
try {
wallpManager.setResource(newInt);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(UILPager.this, cs, Toast.LENGTH_SHORT).show();
}
});
Set wallpaper from URL
try {
URL url = new URL("http://developer.android.com/assets/images/dac_logo.png");
Bitmap bitmap = BitmapFactory.decodeStream(url.openStream());
wallpaperManager.setBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Enjoy =)
A method wallpaperManager.setResource() requires resource id from your application. Example: I've ImageView with id "myImage" then call the method will look like as wallpaperManager.setResource(R.id.myImage).
In your case your id not valid.
Instead of wallpManager.setResource(0) you should use the wallpManager.setResource(R.drawable.yourimage) since it's expecting a drawable and there is none in your app with id = 0.
In your code
String newStr = images[position];
int newInt = 0;
try{
newInt = Integer.parseInt(newStr);
} catch(NumberFormatException nfe) {
}
Since newStr is never a number, always a url so NumberFormatException is caught always. Hence the value of newInt is always initialized to 0. Hence the error.
I realized that I have to download the image before I can set it as wallpaper! Thanks for your help AndroidWarrior and Owl. When I get the download code worked out, I'll post it. Owl showed me how to download the wallpaper:
//--- Wallpaper button
wallp_BTN.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
vpURL = new URL(images[position]);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
WallpaperManager wallpManager = WallpaperManager.getInstance(getApplicationContext());
try {
Bitmap bitmap = BitmapFactory.decodeStream(vpURL.openStream());
wallpManager.setBitmap(bitmap);
Toast.makeText(UILPager.this, "The wallpaper has been set!", Toast.LENGTH_LONG).show();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
//--- END Wallpaper button
... and I also figured out how to download the ViewPager image as well (I need to do both in different areas of my app):
//--- Wallpaper button
wallp_BTN.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String vpURLStr = images[position];
GetVPImageTask downloadVPImageTask = new GetVPImageTask();
downloadVPImageTask.execute(new String[] { vpURLStr });
}
});
//--- END Wallpaper button
//--- Download ViewPager Image AsyncTask
private class GetVPImageTask extends AsyncTask<String, Void, Bitmap> {
ProgressDialog getVPImageDia;
#Override
protected void onPreExecute() {
super.onPreExecute();
getVPImageDia = new ProgressDialog(UILNPPager.this);
getVPImageDia.setMessage("Grabbing the image...");
getVPImageDia.setIndeterminate(false);
getVPImageDia.show();
}
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
try {
getVPImageDia.dismiss();
getVPImageDia = null;
} catch (Exception e) {
// nothing
}
Toast.makeText(UILNPPager.this, "The image be Downloaded!", Toast.LENGTH_SHORT).show();
//downloaded_iv.setImageBitmap(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
//--- END Download ViewPager Image AsyncTask
I'm having some troubles displaying an image I am fetching from a URL into an ImageView. With the code I have at the moment, I am getting absolutely nothing. Is there a problem with this code?
Drawable img = image.LoadImageFromWeb(icon);
imageView.setImageDrawable(img);
public static Drawable LoadImageFromWeb(String iconId) {
try {
String url = "http://ddragon.leagueoflegends.com/cdn/4.3.12/img/profileicon/" + iconId + ".png";
InputStream is = (InputStream) new URL(url).getContent();
Drawable icon = Drawable.createFromStream(is, "src name");
return icon;
} catch (Exception e) {
return null;
}
}
try this function
private void downloadImage()
{
Bitmap bitmap = null;
try {
URL urlImage = new
URL("http://ddragon.leagueoflegends.com/cdn/4.3.12/img/profileicon/" + iconId +
".png");
HttpURLConnection connection = (HttpURLConnection)
urlImage.openConnection();
InputStream inputStream = connection.getInputStream();
//****bitmap is your image*****
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and use asyncTask to wait until downloading the image like this
private class Asyn_SaveData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
//get the random string from prefs
if (context != null)
downloadImage();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//do what you want after the image downloaded
}
}
Note: AsyncTask must be subClassed, and after the doInBackground finish its job it calls automatically the onPostExecute
I have code that i was copying from another project that will allow you to pass it a url and it will return a picture...then you set it to an image view and it will display the picture...but somewhere down the line...it isn't displaying the retrieved picture anymore...can you guys look at this code and tell me if there is something wrong???
CLICK EVENT
void NextPic(View v)
{
picNum++; //int holding what pic number we are on
Drawable bPic = LoadImageFromWebOperations(picData[]); //picData = String[] with url data in it
imgView.setImageDrawable(bPic); //Cast earlier in the code
}
Get Pic Function
private Drawable LoadImageFromWebOperations(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}
catch(Exception e)
{
//Custom error handler
uu.SendError(e.getMessage(), "Main.GetPickTask.LoadImageFromWeboperations(String url)");
return null;
}
}
LogCat shows nothing at all...there are no error caught...and the pic keeps coming up blank...i even used the ic_launcher graphic as a placeholder so see if it was the imageview itself...but that shows up for a few seconds and then goes black
Here is an example URL i am using
http://app.guycothal.com/Funnys/2012722133515231.jpg
private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
try {
InputStream is = (InputStream) fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
I want to set ImageView bitmap from our network drive. But i getting Unable to connect to server: Unable to log in to server (PASS): 141.11.11.247 error.
Here is my download ant setBitmap code for this :
public class ResimCek implements Runnable {
int resimID = 0;
public ResimCek(int parcaID) {
// store parameter for later user
resimID = parcaID;
}
public void run() {
try {
ImageView resim = (ImageView) findViewById(resimID);
Bitmap bitmap = BitmapFactory
.decodeStream((InputStream) new URL(
"file://141.11.11.247/foto_metod/Parca/"
+ Integer.toString(resimID) + ".jpg")
.getContent());
resim.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is my last code :
public class ResimCek implements Runnable {
int resimID = 0;
public ResimCek(int parcaID) {
// store parameter for later user
resimID = parcaID;
}
public void run() {
int resID = getResources().getIdentifier(Integer.toString(resimID) , "tag", getPackageName());
ImageView resim = (ImageView) findViewById(resID);
Drawable image = ImageOperations(getBaseContext(),"http://141.11.11.206/parca/" + Integer.toString(resimID) + ".jpg" ,"I" + Integer.toString(resimID) + ".jpg");
// ******************************************************
resim.setImageDrawable(image); // I GOT THE ERROR HERE!!!
}
}
private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(new URL(url).openConnection().getInputStream(),saveFilename);
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
Thanks for your help.
may be you forgot to declare internet permission in your manifest file, check it please.
Download FtpClient
And use username and password to login.
Look at this documentation, hope it will help you.
In my app, when you click on the button then I am downloading the images from the url's. It displaying the images some time correctly but some time it display empty. *problem is some times bitmap object(i.e, "result" in code ) return null.*please can anybody help me.
Following is my code
try
{
String ImageUrl = ((eachReview)RB_Constant.revht.get(title_value)).UserImageUrl;
System.out.println("Image Url:"+ImageUrl);
if(ImageUrl != null)
{
DownLoadImageInAThreadHandler(ImageUrl,holder);
}
else
{
System.out.println("Image url is null then display the default image");
holder.userImage.setImageResource(R.drawable.defaultuserimage);
}
}
catch(Exception e){
System.out.println("Error from Userimage fetching.."+e.toString());
}
private void DownLoadImageInAThreadHandler(final String imgurl,final ViewHolder holder)
{
//Thread for getting the attributes values
Thread t = new Thread()
{
public void run()
{
try
{
Bitmap drawable = getDrawableFromUrl(imgurl);
System.out.println("Drawable(after downloading):"+drawable);
if(drawable != null)
{
holder.userImage.setImageBitmap(drawable);
}
else
{
System.out.println("after downloading drawable is null then set the default image");
holder.userImage.setImageResource(R.drawable.defaultuserimage);
}
}
catch(Exception exp)
{
System.out.println("Exception in DownLoadImageInAThread : " + exp.getMessage());
}
}
private Bitmap getDrawableFromUrl(String imageUrl)
{
try
{
URL myFileUrl = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
final Bitmap result = BitmapFactory.decodeStream(is);
is.close();
new Thread() {
public void run() {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if(result != null)
{
result.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
}
}
}.start();
return result;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
};
t.start();
}
Try making you getDrawableFromUrl as:
public static Drawable getDrawableFromUrl(String url) {
Drawable image = null;
try {
InputStream in = (java.io.InputStream) new java.net.URL(url).getContent();
if (in != null) {
image = Drawable.createFromStream(in, "image");
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return image;
}
Also do not compress image within same function. Try Doing it after you successfully receive an image. One thing more that write getDrawableFromUrl function out of the thread but in same class. Hope this works for you.