I am using this code to download a profile picture (https://graph.facebook.com/19292868552/picture) from Facebook using the Android Facebook SDK:
asyncFacebookRunner.request("19292868552" + "/picture", new BaseRequestListener() {
#Override
public void onComplete(String response, Object state) {
System.out.println(response);
byte[] imageBytes = response.getBytes();
Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
System.out.println(bitmap);
}
#Override
public void onException(Exception ex) {
}
});
The problem is, that the bitmap is null. This is the logcat:
11-10 20:15:56.540: I/System.out(20930): ������JFIF����������������;CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 95����C�� ����C������2��2"�������������������������� �����������}��!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz������������������������������������������������������������������������������������������� ���������w��!1AQaq"2�B���� #3R�br�$4�%�&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������������?������{���(�B�K#UQ�$��l�?�^�/��τV�x�TL�j�X�}A����!��_�u�����f���ɨxW����A9�O����&`É�c��$���G��O���G����=�7;b'���8�F�OZ��xS�������Q�u����Yy�3�f�=GF���_�c뿊�V�3�~�{��7>6���H-"�%�������7�#��1S�e���kS���ߦ]���m�J�O�۴� T0�rJ�V��MX�?g���I�_c��λg����jJ$Dtr�mmFK����`�N�+̾.��_���ioK�/�����e�����y$y��|���9���?P�V�<=v��[z+uQ�C��zШ��{�^���/�*���H��woc>��[LM��F�bu$��P����Gב][M#���Ċ� S�p}8#�������.?fOY�y��_��Ki&����,v�:23q��`1�O85�����������NxSO�_�]F8����z�w31��[��Edl�ʱ�|�k��NUprQ�cv��ڻ~���S��g��ɷ��'o�W���=��QFW��������~���}������,��Uԫ���$�'�5�ľ�.���S3Aye;G$g)є��k��s�w���v�O��?�tԫ���t^c��_��oG�1�?�_����Z��~��G����]G��V��Wx��/�_0��P��O"67���$�_{>Z��^r>���i�>�"�>�t+I%�d���J��˕y$?<�;�B�W���$��=4��?�Y�������4߉��x[�M݆��M�Q��[<� A�7d��^�,e9�o���h��)RN�yw������������+�;"����h�'�4M7���^��� ��1�!`��P�G���ƖD�о��v��K?��5�I���������_��.�.����fQ��R���$�bc���v.���$�{~Ǻq�㧁�+�|g�����yeW6�q�$��$���վ���,e:Q]V��^���D�ޯ�ڊ8��h�ď�������.G�����7A�~j�چ��t���0��;��đN�f��F��0�ߞ+��9����9�<���9�[��qab����p�8��8����_�,���)YP�+¿m��y�����Ho��Y��۷�y������r�ڤ��6�ܭ�_a��^#N�����+�[}�߿K�>3*�^n�>7��Ƙ��_O�i���_u����h���㧅,��1j�^9�H�յij�ƞ�7v�$��%�##Q��2p0{?�+G��?���&��~��-j][7"ԣO��3[�w_1�2�#)�{h��!�����>1|E����o��rt_kZN��j�jb�%��H���$��s�Fp9�����s\��I4��֭'�v�եe��>s��zPK�R����+�U�wt�OW���+1s!���8��ز��������������<[�O�I���4M7V��Y�(H��G*Ɉ��v������_�~)����Gč3⿍�%g{�i_f��O0[)r䪟�>O��Gb+����,b�ª����+��u\GO����Ԥ����
11-10 20:15:56.540: D/skia(20930): --- SkImageDecoder::Factory returned null
11-10 20:15:56.540: I/System.out(20930): null
How can I get a bitmap to show in an ImageView?
Everything looks correct to me, you also get input as the print shows. I found an another examplehere for user picture. The example uses Url and inputstream indstead of byte array, maybe that would work for you.
Using the new Facebook SDK this problem doesn't occur anymore.
Related
can you give me some reference about imageSlider from json?
I can already convert base64 to bitmaps using listView. but I am confused about how to display the results of the conversion into imageSlider.
data:[{"ID": 1,"Title": "Ads","Image":"data:image\/jpeg;base64........"]
This method can help:
private void setExistImage(ImageView imageView, String base64String){
if (!base64String.isEmpty()) {
byte[] bytes = Base64.decode(base64String, Base64.DEFAULT);
imageView.setImageBitmap(BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
}
}
Maybe you can give a try to retrofit or picasso they are most popular libraries used in Android nowadays
I am referring Google Places photo android api.
I am using below code in onBindViewHolder of RecyclerView Adapter.
Half the time it throws Illegal State exception. Please help.
final Task<PlacePhotoMetadataResponse> photoMetadataResponse = mGeoDataClient.getPlacePhotos(placeId);
photoMetadataResponse.addOnCompleteListener(new OnCompleteListener<PlacePhotoMetadataResponse>() {
#Override
public void onComplete(#NonNull Task<PlacePhotoMetadataResponse> task) {
// Get the list of photos.
PlacePhotoMetadataResponse photos = task.getResult();
// Get the PlacePhotoMetadataBuffer (metadata for all of the photos).
PlacePhotoMetadataBuffer photoMetadataBuffer = photos.getPhotoMetadata();
// Get the first photo in the list.
PlacePhotoMetadata photoMetadata = photoMetadataBuffer.get(0);
// Get the attribution text.
CharSequence attribution = photoMetadata.getAttributions();
// Get a full-size bitmap for the photo.
Task<PlacePhotoResponse> photoResponse = mGeoDataClient.getPhoto(photoMetadata);
photoResponse.addOnCompleteListener(new OnCompleteListener<PlacePhotoResponse>() {
#Override
public void onComplete(#NonNull Task<PlacePhotoResponse> task) {
PlacePhotoResponse photo = task.getResult();
Bitmap bitmap = photo.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Glide.with(mContext)
.load(stream.toByteArray())
.asBitmap()
.error(R.drawable.cast_album_art_placeholder)
.centerCrop()
.thumbnail(.2f)
.into(holder.placeImage);
}
});
}
});
StackTrace :
E/UncaughtException: java.lang.IllegalStateException
at com.google.android.gms.common.internal.zzbp.zzbg(Unknown Source)
at com.google.android.gms.common.data.zzc.zzbu(Unknown Source)
at com.google.android.gms.common.data.zzc.<init>(Unknown Source)
at com.google.android.gms.location.places.internal.zzav.<init>(Unknown Source)
at com.google.android.gms.location.places.internal.zzar.<init>(Unknown Source)
at com.google.android.gms.location.places.PlacePhotoMetadataBuffer.get(Unknown Source)
Even if thi issues is almost one year old and since the given answer didn't solve my error, I'll share my solution:
// Get the first photo in the list.
if (photoMetadataBuffer.getCount() > 0) {
PlacePhotoMetadata photoMetadata = photoMetadataBuffer.get(0);
// continue with your code
}
This, because the photoMetadataBuffer isn't null.
But yes, the error happens only for places without pictures.
I am fairly certain that the issue is that your application is crashing due to the fact that you are attempting to retrieve a photo from a location that does not have a photo to display. You must do a null check before attempting to retrieve the first photo in your photoMetadataBuffer.get(0). This is a good example of how Google's documentation is somewhat incomplete from the example code that is provided. You should have something like the following:
// Get the first photo in the list.
if (photoMetadataBuffer != null) {
PlacePhotoMetadata photoMetadata = photoMetadataBuffer.get(0);
// continue with your code
}
If the photoMetadataBuffer is null, then there isn't a photo to be displayed and you can handle your application logic appropriately, such as loading a default image, giving feedback to the user, or not displaying the ImageView.
Question 1: Is it possible to download image file without giving the reference to ImageView?
Question 2: Can i download each file in a separage instance of aQuery or do i have to download the file sequentially? e.g, waiting for the callback of current file download and then trigger the next file download call? Below is my code
// Ad is my custom model class
// adList is my list of Ads having URL's to the ads hosted somewhere
// imageView is an invisible imageView as downloading does not start if i don't give any reference to any imageView resource
for (String adUrl : adList) {
if (adUrl.length() > 0) {
AQuery aQuery = new AQuery(DownloadAdActivity.this);
BitmapAjaxCallback callback = new BitmapAjaxCallback();
callBack.url(adUrl);
callBack.fallback(R.id.placeHolderResource);
callBack.fileCache(true);
callBack.memCache(true);
aQuery.id(imageView).image(callBack);
}
}
I need to download 20/30 images when the app starts first time, so far i am doing it by giving a hidden imageView reference and trigging the aQuery sequentially after each image has downloaded. I tried to generate 20/30 request in a loop but only the last aQuery trigger call works which cancels the previous image download call.
Please guide me:
1- How to cache images without giving any reference to the imageView
2- How to download images in parallel manner, not in sequential manner through AQuery.
1) You can use ajax call without ImageView reference to download image.
androidQuery.ajax("url", Bitmap.class, 0, new AjaxCallback<Bitmap>() {
#Override
public void callback(String url, Bitmap bitmap, AjaxStatus status) {
super.callback(url, bitmap, status);
}
});
2) By default you can download 4 images concurrently. But you can change as per your requirement like this
AjaxCallback.setNetworkLimit(8);
You can use Picasso
It will make all the downloads and also the caching for the images.
Anyway if the images are quite small you should prepare a "zip" file and dl all of them with an AsyncTask / Thread and unzip them. Opening and closing the connections to the server are "very expensive" operations in time consuming.
Here is method to obtain bitmap from url using AQuery
static Bitmap myBitmap = null;
public static Bitmap getBitmapFromURL(String src) {
try {
Log.i(TAG, "Image Url is : " + src);
AQuery androidQuery = new AQuery(ChatApplication.getInstance());
androidQuery.ajax(src, Bitmap.class, 0, new AjaxCallback<Bitmap>() {
#Override
public void callback(String url, Bitmap bitmap, AjaxStatus status) {
super.callback(url, bitmap, status);
if (bitmap != null)
myBitmap = bitmap;
}
});
} catch (Exception e) {
Log.i(TAG, "Error due to " + e);
}
return myBitmap;
}
AQuery aq = new AQuery(context);
aq.ajax(url_of_image, Bitmap.class, new AjaxCallback<Bitmap>() {
#Override
public void callback(String url, Bitmap object, AjaxStatus status) {
}
});
Im sorry for replying late,But this is best library I have ever came across.
Yes,You can download. Bitmap object will give you the image.
You can create multiple instances of Aquery if you want to download or pass the each URL after one download finishes,you can use any loop for that.
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 have an Image on my server. The URL for the image is something like:
http://www.mydomain.com/123456uploaded_image.jpg
I am trying to set this image to my ImageView. Here is the code that I tried:
try{
String url1 = myeventimagearray[position];
URL ulrn = new URL(url1);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = (InputStream) con.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
iveventimg.setImageBitmap(bmp);
else
Log.i("Image","Not set");
} catch(Exception e) {
e.printStackTrace();
}
When I try this, my imageview is empty, i.e., it doesn't set the image view and i get this System err in my logcat:
java.lang.ClassCastException: libcore.net.http.FixedLengthInputStream cannot be cast to com.example.eventnotifier.Base64$InputStream
Base46.java is a file I found from the internet that Encodes and decodes to and from Base64 notation.
Any idea why I'm getting this System.error?
Thank you
Use URlImageViewHelper, it will take care of loading url into imageview.
Refer this
It will take care of caching, loading in background etc. by itself.
This is not an easy answer but you should use a caching system.
See https://github.com/chrisbanes/Android-BitmapCache for an excellent one!
Simply swap the ImageView for NetworkCacheableImageView and then use loadImage( "http://....", true );
You are likely getting an exception because you are trying to do network io on the main thread. Consider using a loader or an AsyncTask to load your image.
Check your logs, I bet you are printing a stack trace in the auto generated catch block.
new Thread(new Runnable() {
public void run() {
final Bitmap b = bitmap = BitmapFactory.decodeStream((InputStream)new URL(myeventimagearray[position]).getContent());
iveventimg.post(new Runnable() {
public void run() {
iveventimg.setImageBitmap(b);
}
});
}
}).start();
Use Picasso to fetch image from url. Implement 'com.squareup.picasso:picasso:2.71828' in build.gradle and in java
Picasso.get()
.load(url) // http://www.example.com/123456uploaded_image.jpg
.resize(50, 50)
.centerCrop()
.into(imageView)