I currently have an arraylist as follows:
private void loadImages() {
images = new ArrayList<>();
images.add(getResources().getDrawable(R.drawable.imag1));
images.add(getResources().getDrawable(R.drawable.imag2));
images.add(getResources().getDrawable(R.drawable.imag3));
}
I want to be able to convert a url into these drawables such that:
drawable1 = "http.someimage.com/image.png"
drawable2 = "http.someimage.com/newimage.png"
followed by
private void loadImages() {
images = new ArrayList<>();
images.add(getResources().getDrawable(drawable1));
images.add(getResources().getDrawable(drawable2));
...etc }
Is there any easy way to go around this? I definitely want to stick to drawables ,but I cant find any way to convert a url to drawable
Any ideas? Thanks!
If you have a URL of the picture you need to download it first.
You can't "convert" a URL into a drawable.
you need something like this:
URL url = new URL("http.someimage.com/image.png");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
Then if you need to add the image into an ImageView object you can call the method .setImageBitmap(bmp).
Otherwise there are ways to extract a Drawable object from the Bitmap
you can check this previous answer. then once you have the drawable you can add it to your arraylist.
Hope I got your question right
P.S.: be sure not to do this on main thread since it is a network operation! use a thread or an asynctask
Related
I'm using ION (https://github.com/koush/ion) to load images from the web into a ListView of ImageView. Currently I want to get the bitmap from the ImageView, but I'm getting one exception that is force closing my app:
java.lang.ClassCastException: com.koushikdutta.ion.IonDrawable cannot be cast to android.graphics.drawable.BitmapDrawable
These are the lines that I'm using:
final ImageView itemImageView = (ImageView)view.findViewById(R.id.photoImage);
final Bitmap itemDrawable = ((BitmapDrawable) itemImageView.getDrawable()).getBitmap();
How can I solve this? Thanks in advance!
Ion sets a custom drawable to manage animated GIFs, fade transitions, etc, so it can't be cast to a BitmapDrawable.
Use:
Ion.with(imageView).getBitmap()
to get the bitmap out
If you set a callback when making the Ion request and have it return an ImageViewBitmapInfo you can retrieve bitmaps that way. For e.g.
Ion.with(imageView)
.placeholder(R.drawable.default_avatar)
.load(userImageURL)
.withBitmapInfo()
.setCallback(new FutureCallback<ImageViewBitmapInfo>() {
#Override
public void onCompleted(Exception e, ImageViewBitmapInfo result) {
// Check for exceptions
// Check bitmaps first
Bitmap b = result.getBitmapInfo().bitmaps[0];
...
};
It may be worth looking into:
nostra13's "Universal Image Loader"
It's an awesome library with tons of features to display images from URLs, cast to bitmaps, etc.
if(imageView.getDrawable() instanceof BitmapDrawable)
bm = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
else { /***to check if it is ION drawable, use ION*/
bm = Ion.with(imageView).getBitmap();
}
I'm downloading files with my app via an API (this is working perfectly). Later in my app I'm doing a call to my database to get the file info: id, name, location and return it as a HashMap:
HashMap<Integer, ArrayList<String>> imgTitle;
I take the returned HashMap, extract the ArrayList and use that to populate some buttons. the array list holds the filename and file location. When the page loads the names display correctly but the images don't always load or one loads. If I go back and reenter the activity (via a button press) I'll get different images showing up. I've sent my array to the log and the file location is present and correct for all arrays. Why are only some image showing?
for (Map.Entry<Integer, ArrayList<String>> e : imgTitle.entrySet()) {
...
ArrayList<String> catList = e.getValue();
final String catTitle = catList.get(0);
File indexImage = new File(catList.get(1));
// add images
ImageButton imgButton = new ImageButton(this);
imgButton.setImageURI(Uri.fromFile(indexImage));
...
}
The above is inside a method called on the onCreate. My assumption is maybe the setImageURI is too slow? Any ideas?
Prior to using the setImageURI I used
imgButton.setImageResource(R.drawable.test_vehicle);
as a placeholder it was working fine. However, now I have to use a file that was downloaded and saved locally.
You could try to decode a Bitmap from a stream, like this:
File indexImage = new File(catList.get(1));
InputStream imageStream = new FileInputStream(indexImage);
Bitmap backgroundImage = null;
try {
backgroundImage = BitmapFactory.decodeStream(imageStream);
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
//Dispose of the temporary resources
imageStream.close();
imageStream = null //So that the stream is deleted on next GC
}
catch(IOException e) {
e.printStackTrace();
}
}
if (backgroundImage != null) {
ImageButton imgButton = new ImageButton(this);
imgButton.setImageBitmap(backgroundImage);
backgroundImage.recycle();
}
Note: This is pure speculation, I haven't tested any of this. It's simply the first solution that came to my mind
here i want to display a image logo which i am receiving from a sqlite as blob database when i dont have internet, though i know its a not a good practice but i want to make it simpler this way.
Problem i am facing is i am able to receive image in log but some warning (link below) is coming because of which it is not loading it into imageView.
Here's the warning i am getting in log !!
I am unable to figure out why it still running DownloadImageTask which is a async task even when not online that is isOnline()==false !!
ImageView logo = (ImageView)findViewById(R.id.Logo);
Bundle extras = getIntent().getExtras();
if(isOnline(this)==true);
{
String link = extras.getString("Logo1");
new DownloadImageTask(logo).execute(link);
}
if(isOnline(this)==false){
Log.d("offline","image");
Log.d("offline",extras.getByteArray("Logo2").toString());
//getting these ^^ in log
byte[] outImage=(byte[]) extras.getByteArray("Logo2");
if(outImage!=null)
{
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
logo.setImageBitmap(theImage);
}
}
}
if(isOnline(this)==true)//you Superfluous add a ";" in this
{
String link = extras.getString("Logo1");
new DownloadImageTask(logo).execute(link);
}
i am a newbie,hope can help you
I'm working on implementing a website's API in an Android app. There's a part of this API which gives me an array, which contains an array of image URLs. Now, I can iterate through the arrays just fine, and I have written an AsyncTask that transforms image URLs into drawables. But I don't have a good way to get those drawables into the ImageView (which I am creating programatically in the loop):
void createPhotoPost(JSONObject postData, LinearLayout myPostHolder) {
try {
ImageView myImage = new ImageView(myContext);
JSONArray photosArray = new JSONArray(postData.getString("photos"));
for(int i = 0; i < photosArray.length(); i++) {
JSONObject thisPhoto = photosArray.getJSONObject(i);
JSONArray sizesArray = new JSONArray(thisPhoto.getString("alt_sizes"));
JSONObject largest = sizesArray.getJSONObject(0);
new GetPhotoSet(this).execute(largest.getString("url"));
}
myPostHolder.addView(myImage);
} catch (Exception e) {
e.printStackTrace();
}
}
The function I posted above is called from within another loop. As you can see in my code above, the ImageView myImage needs to eventually contain the drawable that is returned by the execute call of GetPhotoSet.execute. Any ideas? Thanks!
Additional details: Since the method where the data is returned by the AsyncTask is outside of the loop where I declared the ImageView myImage, it doesn't know that myImage exists, and it can't reference it (and there are presumably a handful of myImages by this point, from different iterations of the loop)
Nick, that's what onPostExecute() is for. Create your ImageView in onPostExecute() and add it to your Activity from there. If you are looping over a series of images, you can also use publishProgress() to do this. In your example you should move the entire loop to your task's doInBackground().
For some reason d=null when creating a drawable from coverArtURLStr, which is the full http path to the resource on the LAN.
Anything obvious wrong? It's a path to a .png
[I can access the LAN OK, and Data.defaultCoverArt works fine]
public static void updateCoverArt(String coverArtURLStr)
{
String coverArtURL = coverArtURLStr;
Drawable d;
if (coverArtURL.equals(""))
d = Data.defaultCoverArt;
else
d = Drawable.createFromPath(coverArtURL);
Data.coverArtIV.setImageDrawable(d);
}
I don't think Drawable.createFromPath() method can handle URLs. Try this solution Android Drawable Images from URL.