Android, Make an image at a URL equal to ImageView's image
To download an image and set it as content for an imageview
try {
ImageView i = (ImageView)findViewById(R.id.image);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Display image from URL into ImageView?
Ok I added it and included the .jar but it doesnt work, the app just crashes, I think this is the relevant part to solve this issue:
try {
mComments = json.getJSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
//gets the content of each tag
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
String url = c.getString(TAG_URL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
map.put(TAG_URL, url);
// PART TO GET IMAGES - "Can not resolve context"
ImageView imageView = (ImageView) findViewById(R.id.url);
Picasso.with(context).load(url).into(imageView);
// adding HashList to ArrayList
mCommentList.add(map);
//annndddd, our JSON data is up to date same with our array list
}
EDIT
When I started to build the app, I created 2 posts with direct file paths of the images, where they are stored at the device, they are displayed correct:
Screenshot
The uploaded images are not displayed, they have a url like this:
"http://www.eywow.com/webservice/uploads/name.jpg"
URL into a ImageView
you can use one of the following links:
http://androidexample.com/Download_Images_From_Web_And_Lazy_Load_In_ListView_-_Android_Example/index.php?view=article_discription&aid=112&aaid=134
http://sunil-android.blogspot.in/2013/09/lazy-loading-image-download-from.html
https://github.com/commonsguy/cwac-endless/blob/master/demo/src/com/commonsware/cwac/endless/demo/EndlessAdapterCustomTaskFragment.java
How to display image from URL on Android
You can directly show image from web without downloading it. Please check the below function . It will show the images from the web into your image view.
public static Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
then set image to imageview using code in your activity.
Trying to fill an imageview with an image from a url
I ended up using an asynctask to make this work:
class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private int data = 0;
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
@Override
protected Bitmap doInBackground(Integer... params) {
data = params[0];
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://static.adzerk.net/Advertisers/11239ce559004d9a8e16fe2790630628.png").getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
// Once complete, see if ImageView is still around and set bitmap.
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
Android - Loading Image Url and Displaying in ImageView
try with this class, it download the image in background and store in cache:
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
/**
* This Class is for download images and assign the drawable to an ImageView.
*
*/
public class DrawableBackgroundDownloader {
private final Map<String, Drawable> mCache = new HashMap<String, Drawable>();
private final LinkedList <Drawable> mChacheController = new LinkedList <Drawable> ();
private ExecutorService mThreadPool;
private final Map<ImageView, String> mImageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
public static int MAX_CACHE_SIZE = 80;
public int THREAD_POOL_SIZE = 3;
/**
* Constructor
*/
public DrawableBackgroundDownloader() {
mThreadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
}
/**
* Clears all instance data and stops running threads
*/
public void Reset() {
ExecutorService oldThreadPool = mThreadPool;
mThreadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
oldThreadPool.shutdownNow();
mChacheController.clear();
mCache.clear();
mImageViews.clear();
}
/**
* Load the drawable associated to a url and assign it to an image, you can set a placeholder to replace this drawable.
* @param url Is the url of the image.
* @param imageView The image to assign the drawable.
* @param placeholder A drawable that is show during the image is downloading.
*/
public void loadDrawable(final String url, final ImageView imageView,Drawable placeholder) {
if(!mImageViews.containsKey(url))
mImageViews.put(imageView, url);
Drawable drawable = getDrawableFromCache(url);
// check in UI thread, so no concurrency issues
if (drawable != null) {
//Log.d(null, "Item loaded from mCache: " + url);
imageView.setImageDrawable(drawable);
} else {
imageView.setImageDrawable(placeholder);
queueJob(url, imageView, placeholder);
}
}
/**
* Return a drawable from the cache.
* @param url url of the image.
* @return a Drawable in case that the image exist in the cache, else returns null.
*/
public Drawable getDrawableFromCache(String url) {
if (mCache.containsKey(url)) {
return mCache.get(url);
}
return null;
}
/**
* Save the image to cache memory.
* @param url The image url
* @param drawable The drawable to save.
*/
private synchronized void putDrawableInCache(String url,Drawable drawable) {
int chacheControllerSize = mChacheController.size();
if (chacheControllerSize > MAX_CACHE_SIZE)
mChacheController.subList(0, MAX_CACHE_SIZE/2).clear();
mChacheController.addLast(drawable);
mCache.put(url, drawable);
}
/**
* Queue the job to download the image.
* @param url Image url.
* @param imageView The ImageView where is assigned the drawable.
* @param placeholder The drawable that is show during the image is downloading.
*/
private void queueJob(final String url, final ImageView imageView,final Drawable placeholder) {
/* Create handler in UI thread. */
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
String tag = mImageViews.get(imageView);
if (tag != null && tag.equals(url)) {
if (imageView.isShown())
if (msg.obj != null) {
imageView.setImageDrawable((Drawable) msg.obj);
} else {
imageView.setImageDrawable(placeholder);
//Log.d(null, "fail " + url);
}
}
}
};
mThreadPool.submit(new Runnable() {
public void run() {
final Drawable bmp = downloadDrawable(url);
// if the view is not visible anymore, the image will be ready for next time in cache
if (imageView.isShown())
{
Message message = Message.obtain();
message.obj = bmp;
//Log.d(null, "Item downloaded: " + url);
handler.sendMessage(message);
}
}
});
}
/**
* Method that download the image
* @param url The url image.
* @return Returns the drawable associated to this image.
*/
private Drawable downloadDrawable(String url) {
try {
InputStream is = getInputStream(url);
Drawable drawable = Drawable.createFromStream(is, url);
putDrawableInCache(url,drawable);
return drawable;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* This method manage the connection to download the image.
* @param urlString url of the image.
* @return Returns an InputStream associated with the url image.
* @throws MalformedURLException
* @throws IOException
*/
private InputStream getInputStream(String urlString) throws MalformedURLException, IOException {
URL url = new URL(urlString);
URLConnection connection;
connection = url.openConnection();
connection.setUseCaches(true);
connection.connect();
InputStream response = connection.getInputStream();
return response;
}
}
is easy to use just declare:
DrawableBackgroundDownloader drawableDownloader = new DrawableBackgroundDownloader();
and where do you want to use:
drawableDownloader.loadDrawable(String urlImage, ImageView iView,Drawable drawable);
where drawable is a Drawable that is showing during image download.
Android compare imageView with image
Thanks Morrison, that was it.
First
final ImageView test = (ImageView) findViewById(R.id.imageview1);
final Bitmap bmap = ((BitmapDrawable)test.getDrawable()).getBitmap();
Drawable myDrawable = getResources().getDrawable(R.drawable.red);
final Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
Next
if(bmap.sameAs(myLogo))
{
do sthng
}
Displaying an image from url on Fragment
If you access the views in your fragment then you need access it as view.findViewById
as i have done below:
Try out as below:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pages, container, false);
try {
ImageView i = (ImageView)rootView.findViewById(R.id.image);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return rootView;
}
Related Topics
Difference Between Android-Support-V7-Appcompat and Android-Support-V4
How to Represent a "Many to Many" Relation with Android Room When Column Names Are Same
Detect When Recyclerview Reaches the Bottom Most Position While Scrolling
Android Type_Linear_Acceleration Sensor - What Does It Show
Phonegap/Cordova Android Development
Google Maps API V2 Draw Part of Circle on Mapfragment
Passing Strings Between Activities in Android
Fit Image in Imagebutton in Android
Can't Accept License Agreement Android Sdk Platform 24
Android Device Chooser - My Device Seems Offline
How to Export Library to Jar in Android Studio
Memory Leaks with Custom Font for Set Custom Font
Is There Any Way in Android to Force Open a Link to Open in Chrome
How to Get Android Device Screen Size
Android O - Old Start Foreground Service Still Working
How to Change the Package Name of an Android App on Google Play