Updating an ImageView with an image from a URL - java

Within my android application, I'm wanting to update an ImageView, with an image specified from a URL. This URL has been fetched via an API as part of an AsyncTask.
I have defined the ImageView as follows:
<ImageView
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:layout_height="wrap_content"
android:id="#+id/product_image"
android:src="#drawable/no_product_image"
android:layout_marginRight="6dip"
android:layout_width="wrap_content"
/>
That way, whilst the data is loading, there is a blank image present behind a ProgressDialog.
As part of the doInBackground of the AsyncTask, after fetching the product details, I call:
private void createProductScreen(Product product){
Log.i(TAG, "Updating product screen");
//Set the product image
ImageView imgView =(ImageView)findViewById(R.id.product_image);
Drawable drawable = loadImageFromWeb(product.getImageUrl());
imgView.setImageDrawable(drawable);
Log.i(TAG, "Set image");
}
The image is loading from the web as follows:
private Drawable loadImageFromWeb(String url){
Log.i(TAG, "Fetching image");
try{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src");
Log.i(TAG, "Created image from stream");
return d;
}catch (Exception e) {
//TODO handle error
Log.i(TAG, "Error fetching image");
System.out.println("Exc="+e);
return null;
}
}
When this runs I see "Created image from stream" in the log, but don't see "Set image" and the onPostExecute of the AsyncTask is never called.
Does anyone have any ideas on the issue or a better way of updating the image from the blank image to the product image?

You should get an Exception since you are trying to set the ImageView in a separated thread.
imgView.setImageDrawable(drawable); must be called in the same UI thread.
Since you are using the AsyncTask class, the right place for set the imageview object is inside the onPostExecute method.
Change you logic in a way that the doInBackground will returns the Drawable object to the onPostExecute method, then use it calling imgView.setImageDrawable(drawable);

Set Imageview to drawable image
Drawable drawable = loadImageFromWeb(product.getImageUrl());
here is problem.
Drawable drawable = loadImageFromWeb(XXXXUrl);
Imageview.setImageDrawable(drawable);
Give a proper URL to drawable.

Related

Screenshot not captured while agora.io video call Android Java

I have implemented a video calling feature in our app. There is a button which captures the screenshot of specific view. On video call there a two views Local View and Remote View. These are actually Relative and Frame layouts. In this case i want take screenshot of remote view but it's just giving me a blank image. I think somehow agora video calling not allowing it but there should be any settings or something to disable this but that i have not found yet. here is the code:
Setting up remote video:
mRemoteContainer is a RelativeLayout and mRemoteVideo is VideoCanvas by agora.io
Similarly mLocalContainer is FrameLayout.
private void setupRemoteVideo(int uid) {
ViewGroup parent = mRemoteContainer;
if (parent.indexOfChild(mLocalVideo.view) > -1) {
parent = mLocalContainer;
}
if (mRemoteVideo != null) {
return;
}
SurfaceView view = RtcEngine.CreateRendererView(getBaseContext());
view.setZOrderMediaOverlay(parent == mLocalContainer);
parent.addView(view);
mRemoteVideo = new VideoCanvas(view, VideoCanvas.RENDER_MODE_HIDDEN, uid);
mRemoteVideo.view.setWillNotDraw(false);
mRtcEngine.setupRemoteVideo(mRemoteVideo);
}
This function used to get bitmap from the view
private Bitmap getScreenShotFromView(View v) {
Bitmap screeShoot = null;
try {
screeShoot = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(screeShoot);
v.draw(canvas);
} catch (Exception e) {
Log.e("GFG", "Failed to capture screenshot because:" + e.getMessage());
}
return screeShoot;
}
I tried function call with both view but getting black or blank image
Bitmap bitmap = getScreenShotFromView(mRemoteVideo.view);
Bitmap bitmap = getScreenShotFromView(mRemoteContainer);
Your help will be really appreciated for me as i stuck on this issue.
By the way I used the same view capturing technique on iOS with swift
and Its working fine.

ImageButton call setImageDrawable() but get wrong size

I was writing an android application which contains a RecyclerView inside my ActivityMain. Each rows has an imageButton and a textLabel. In onBindViewHolder() method, I download an image from an URL and after using setImageDrawable method, I change the image with the one that I just downloaded.
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
holder.textAuthor.setText(posts.get(position).getAuthorName());
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
// Get URL Image from my ArrayList Posts(which contains imageButton and textLabel)
URL url = new URL(posts.get(position).getImageView());
// Get inputStream from URL
InputStream inputStream = (InputStream) url.getContent();
// Create a drawable which contains my downloaded image
Drawable drawable = Drawable.createFromStream(inputStream, null);
// Change the image with the new one
holder.imageButton.setImageDrawable(drawable);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
All my ImageButton change image correctly downloading from their URL, but the problem is that they have wrong size until I scroll down and after a while I scroll up inside of my RecyclerView using my finger. It sounds like if I have to refresh my View but I don't know how to do this.
Note: all images have different size
I let you some images to explain better my problem:
When I open my application and it starts to download image from URL
When the download is completed the images have wrong size
If I scroll down and after I scroll up I get the images with the correct size
The rest of my codes is here: MainActivty MyAdapter PostClass
XML File which contains ImageButton: my row of RecyclerView
Hope you can help me as always, thank you a lot!
EDIT: I have fixed downloading image using Glide!
Try the following code it worked for me
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="25dp"
android:layout_height="25dp"
app:srcCompat="#drawable/about" />
give your image button fixed height and width then it will work

how to set up a wallpaper app using firebase recyclerview?

I created a wallpaper app ,I'm using Firebase to upload images to a database and shown it to RecyclerView.
I can see the images that I uploaded in Firebase through the RecyclerView and I can also pass that image to a another activity.
but my problem is, I can't set the image as wallpaper, when I set the button the image is disappearing.
my code to set wallpaper:
img = (ImageView) findViewById(R.id.images);
Intent intent = getIntent();
String webUrl = intent.getStringExtra("URL");
Picasso.get().load(webUrl).into(img);
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WallpaperManager wallpaper = WallpaperManager.getInstance(getApplicationContext());
try {
wallpaper.setResource(+ R.drawable.pug); //by using this code i can set a image in directory a wallpaper
//wallpaper.setResource(+ R.id.images); //i tried this one it doesn't work it just crashes the app
}catch (IOException e){
e.printStackTrace();
}
}
});
what I want is to set any image shown in the ImageView
is there any way
I'm assuming you already have the permission in place for this:
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
I'm not sure what you are trying to achieve, but I am assuming you want the user to choose an image from the list and set it as wallpaper.
You can only pass a Bitmap or Resource ID to WallpaperManager. In this case, fetch the image as a Bitmap first, and then load into the ImageView.
Since you are already using Picasso, you can do this:
Picasso.with(this).load(webUrl).centerCrop().into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
wallpaper.setBitmap(bitmap);
}
}

Android/Java Asynchronous Image Download Task Never Stops Running

I'm attempting parse a JSON payload and place the information in Relative Layout View.
I use this STANDARD asynchronous download routine to obtain the bitmaps to be placed in the appropriate ImageView:
public class AsyncDownloadImage extends AsyncTask<String,Void,Bitmap>{
ImageView bmImage;
public AsyncDownloadImage(ImageView bmImage){
this.bmImage = bmImage;
}
#Override
protected Bitmap doInBackground(String... urls) {
String urldisplay = null;
urldisplay = urls[0];
Bitmap merchViewBitMap = Bitmap.createBitmap(90,90,Bitmap.Config.ARGB_8888);
try{
InputStream in = new URL(urldisplay).openStream();
merchViewBitMap = BitmapFactory.decodeStream(in);
in.close();
}catch(Exception e){
System.out.println(String.format("Image Download Exception ==> %s", e.toString()));
}
return merchViewBitMap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
bmImage.setImageBitmap(result);
}
}
It's called this way in the getView method of the Adapter class:
String imageUrl = String.format("https://www.xxxxxx.com/va/public/render_image?image_id=%s", currentMerchItem.getMt_image_id());
new AsyncDownloadImage(viewHolder.imageview).execute(imageUrl);
The images are downloaded and the ImageView(s) are set, but they are downloaded repeatedly and infinitely. Multiple images seem to be in an ImageView and when scrolled through they change as each is gif.
How do I stop this after the last image in the list is downloaded?!
-TU
The adapters getView method will be called each time the view of the adapter (listview for example) needs to refresh item's view. When you scroll for example you will get many calls to the getview method (depends on the list length ofcourse). At least you need to manage which images are already being loaded from the net in your case. You also have a lot of open source code for lazy loading exactly for cases like yours.
You can also check this thread, it may help you:
Lazy load of images in ListView

Show Urls instead of images Android app

I'm trying to create a simple app that loading photos from a website (like 9gag). I'm using jSoup and asyncTask. The problem is when I'm running the app it shows me only the urls of the images.. what can I do in order to display the image in the listView and not the urls.
XML Prob? Help :-/
![Screen Shot]https://www.dropbox.com/s/moybisjrbdgzjre/Screenshot_2013-04-29-20-09-13.png
here's my LoadImages class:
public LoadImages(ArrayList list, ArrayAdapter adapter)
{
this.list = list;
this.adapter = adapter;
}
#Override
protected Elements doInBackground(String... params) {
org.jsoup.nodes.Document doc = null;
try
{
doc =Jsoup.connect("http://mongol.co.il/").get();
return doc.select("img");
}
catch (IOException e1)
{
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Elements result) {
super.onPostExecute(result);
int flag=0;
//Bitmap bitmap = null;
for ( org.jsoup.nodes.Element div : result )
{
String bla = div.absUrl("src");
list.add(bla);
flag++;
if(flag==3)
break;
}
adapter.notifyDataSetChanged();
}
Here's also my .xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
Thanks In advance!
You're only fetching the URLs at this point. You need to fetch the actual Bitmap data in order to show images. There are two ways to do this:
Download all the images, then show the list after everything is fetched
Show the list immediately with image placeholders, the fetch the images as they're
needed
In general, it's a better experience to respond quickly by showing what you have as you get it (option #2). A ListView is really conducive to this model. In the getView() method of the adapter you'll show the placeholder image while firing off an AsyncTask to get the bitmap. You'll then set Image in onPostExecute. Unfortunately things get messy with View recycling. This basic implementation will result in the wrong image being shown in many cases and a totally unresponsive device if the user scrolls back and forth quickly.
Fortunately, these are problems that others have solved. In fact, there is an excellent set of tutorials along with sample code on Android Developer website.
I have done something like this:
I have a DB with ID, image URL, image URI
image URI is something like file:////mnt/sdcard/<your package>/images/image1.png
I have a place Holder image for each row and in my Arraylist i have put image URI in Arraylist. then in getView method check if that URI file exists or not if not then send a broadcast to download that image(with ID). In downloader I fetch images with corresponding URL.
How to check URI exists: create a file object with URI and call isExists()
How to send broadcast: create an intent put ID in extras then call sendBroadcast(intent)
Now how to refresh list after image has been download: Send another broadcast from onPostExecute() to refresh list and catch that broadcast in your activity and call list.notifyDatasetChanged().
You are adding String to the list
String bla = div.absUrl("src");
list.add(bla);
You need to create custom adapter (for the ListView), which will take that String bla and download the image.
Try this tutorial

Categories