Android picasso get error

Displaying Images with the Picasso Library

Displaying images is easiest using a third party library such as Picasso from Square which will download and cache remote images and abstract the complexity behind an easy to use DSL.

Before Using Picasso , do not forget to add internet permission in the manifest file .

Adding Internet Permission to our Manifest.xml file:

It will allow your app to use internet for downloading images.

Adding Picasso to our app/build.gradle file:

Note: there is a bug with the current version of Picasso that prevents large images (i.e. 10MB) from being loaded, especially with newer camera phones that have larger resolutions. If you are experiencing this issue, you may need to upgrade to the Picasso 2.6.0 snapshot. See the troubleshooting guide to confirm.

To use this snapshot version, you need to add a custom separate Maven repo first:

We can then load a remote image into any ImageView with:

If you are using the latest version of Picasso (2.71828) then remember that with(context) methods is deprecated and is replaced with get() method

We can do more sophisticated work with Picasso configuring placeholders, error handling, adjusting size of the image, and scale type with:

Be sure to use fit() to resize the image before loading into the ImageView. Otherwise, you will consume extra memory, experience sluggish scrolling, or encounter out of memory issues if you render a lot of pictures. In addition to placeholder and error , there is also other configuration options such as noFade() and noPlaceholder() .

We can resize an image with respect to the aspect ratio using resize and specifying 0 for the other dimension as outlined here:

We can combine resizing with certain transforms to make the image appear differently. For example, we can do a center cropping with:

Transform options include centerCrop() (Crops an image inside of the bounds), centerInside() (Centers an image inside of the bounds), fit() (Attempt to resize the image to fit exactly into the target). See this post for more details.

If an image or set of images aren’t loading, make sure to check the Android monitor log in Android Studio. There’s a good chance you might see an java.lang.OutOfMemoryError «Failed to allocate a [. ] byte allocation with [. ] free bytes» or a Out of memory on a 51121168-byte allocation. . This is quite common and means that you are loading one or more large images that have not been properly resized.

First, you have to find which image(s) being loaded are likely causing this error. For any given Picasso call, we can fix this by one or more of the following approaches:

  1. Add an explicit width or height to the ImageView by setting layout_width=500dp in the layout file and then be sure to call fit() during your load: Picasso.with(. ).load(imageUri).fit().into(. )
  2. Call .resize(width, height) during the Picasso load and explicitly set a width or height for the image such as: Picasso.with(. ).load(imageUri).resize(500, 0).into(. ) . By passing 0, the correct height is automatically calculated.
  3. Try removing android:adjustViewBounds=»true» from your ImageView if present if you are calling .fit() rather than using .resize(width, 0)
  4. Open up your static placeholder or error images and make sure their dimensions are relatively small ( AndroidManifest.xml and then add android:largeHeap to your manifest:

Note that this is not generally a good idea, but can be used temporarily to trigger less out of memory errors.

If you experience errors loading images, you can attach a listener to the Builder object to print the stack trace.

We can add a progress bar or otherwise handle callbacks for an image that is loading with:

If we wish to readjust the ImageView size after the image has been retrieved, we first define a Target object that governs how the Bitmap is handled:

Next, we can use the Target with a Picasso call with:

You can still use all normal Picasso options like resize , fit , etc.

Note: The Target object must be stored as a member field or method and cannot be an anonymous class otherwise this won’t work as expected. The reason is that Picasso accepts this parameter as a weak memory reference. Because anonymous classes are eligible for garbage collection when there are no more references, the network request to fetch the image may finish after this anonymous class has already been reclaimed. See this Stack Overflow discussion for more details.

In other words, you are not allowed to do Picasso.with(this).load(«url»).into(new Target() < . >) .

We can use this custom Target approach to create a staggered image view using RecyclerView .

We first need to replace the ImageView with the DynamicHeightImageView.java that enables us to update the ImageView width and height while still preserving the aspect ratio when new images are replaced with old recycled views. We can then set the ratio before the image has loaded if we already know the height:width ratio using onBindViewHolder as shown below:

Alternatively, we can set the ratio after the bitmap has loaded if we don’t know that ratio ahead of time. To avoid using an anonymous class, we will implement the Target interface on the ViewHolder class itself for RecyclerView. When the callback is fired, we will calculate and update the image aspect ratio:

With either of these approaches the staggered grid of images should now render as expected.

You can also use this third-party library for other transformations, such as blur, crop, color, and mask.

To do a rounded corner transformation, you would do the following:

Источник

Picasso — Placeholders, Errors, and Fading

Moonshoot

Moonshoot is a
Student Feature.

After we demonstrated the basic networking, loading and caching capabilities of Picasso in the last three weeks, it’s time to move to more advanced topics. This week, we’ll cover all kinds of placeholders. Picasso does not only display images, it also got your back until the mentioned image is loaded; or if it can’t be loaded at all.

Picasso Series Overview

Getting Started & Simple Loading

Adapter Use (ListView, GridView, . )

How to Deal with Null/Empty Values (in ListViews)

Placeholders, Errors, and Fading

Image Resizing, Scaling and fit()

Callbacks, RemoteViews and Notifications

Advanced ListViews With Images

Image Loading for RecyclerView and CardView

    Placeholders, Errors, and Fading
  1. Image Resizing, Scaling and fit()
  2. Callbacks, RemoteViews and Notifications
  3. Advanced ListViews With Images
  4. Image Loading for RecyclerView and CardView

Ordering Requests by Image Priority

Request Management by Grouping of Images via Tag()

Image Rotation and Transformation

Additional Transformations with Transformation Library

Influencing Image Caching

Cache Indicators, Logging & Stats

Catching and Analyzing Errors

Log Image Loading with Stetho and Chrome Developer Tools

  1. Influencing Image Caching
  2. Cache Indicators, Logging & Stats
  3. Catching and Analyzing Errors
  4. Log Image Loading with Stetho and Chrome Developer Tools

Customizing Picasso with Picasso.Builder

Custom Request Handlers

Integrate OkHttp3 as Network Stack

App Release Preparation

Analyzing Image Loading with Android Studio Profiler

How to Use & Migrate to Picasso’s Upcoming 3.x Version

  1. Integrate OkHttp3 as Network Stack
  2. App Release Preparation
  3. Series Round-Up
  4. Analyzing Image Loading with Android Studio Profiler
  5. How to Use & Migrate to Picasso’s Upcoming 3.x Version

Placeholder: .placeholder()

We probably don’t even have to explain or discuss it: empty ImageView s don’t look good in any UI. If you’re using Picasso, you most likely are loading images via an internet connection. Depending on your users’ environment, this might take a significant amount of time. An expected behavior of an application is to display a placeholder until the image is loaded and processed.

Picasso’s fluent interface makes this very easy to do! Just call .placeHolder() with a reference to a drawable (resource) and Picasso will display that as a placeholder until your actual image is ready.

For obvious reasons, you cannot set an Internet url as placeholder, since that one would be required to be loaded as well. App resources and drawables are guaranteed to be available and accessible. However, for a the load() parameter, Picasso accepts all kind of values. These might not be loadable (no Internet connection, server down, . ), deleted or not accessible. In the next section, we’ll talk about an error placeholder.

Error Placeholder: .error()

Let’s assume our app tries to load an image from a website, which is currently down. Picasso does give us the option to get an error callback and take the appropriate action. While we’ll cover that option later, for now this would be too complicated. In most use cases a placeholder, which signals that the image could not be loaded is sufficient enough.

The call to Picasso’s fluent interface is identical to the previous example for our pre-display placeholder, just with a different function call named error() :

That’s it. If the image you define as load() value cannot be loaded, Picasso will display R.mipmap.future_studio_launcher instead. Once again, acceptable parameters for error() are only already initialized drawable objects or pointers to their resources ( R.drawable. ).

Use of noFade()

No matter if you’re displaying a placeholder before loading the image or not, Picasso automatically fades the image into the ImageView to soften the significant change in your UI. If you wish to directly display the image without the small fade effect, call .noFade() on the Picasso object:

This would directly show you the image, without fading it into the ImageView . Please make sure you’ve a good reason for doing this though!

It is important to know that all these parameters are independent and can be set without relying on each other. For example, you could just set .error() without calling .placeholder() . Any combination of the parameters is possible.

Use of noPlaceholder()

Lastly, you might find a little gem called .noPlaceholder() in the documentation. It’s important to understand, that this does not disable the previously set placeholders via .placeholder() or .error() ! It covers a different use case.

Let’s think about the following scenario: you want to load an image into an ImageView , and after some time you want to load a different image into the same ImageView . With the default configuration, the moment you create the second Picasso call, the ImageView will be cleared by the previous image and the placeholder set by .placeholder() will be displayed. This can look ugly if the ImageView is prominent in your UI and the user notices the possible rapid changes between images within seconds. A better solution is to call .noPlaceholder() in the second Picasso request. This will keep the previous image in place until the second one is loaded. It results in a much smoother experience for your user.

This small code snippet will do exactly what we just described. Immediately after finishing loading the first image, it’ll start the second request. However, thanks to the .noPlaceholder() call, it’ll keep the previous image in place.

Side note: if you’re confused by the .into(imageView, callback) , don’t worry, we’ll explain that in a later post.

Outlook

Hopefully you understood and learned a lot from this blog post. It is tremendously important for a good user experience that the images are not popping in unexpectedly. Also, make it obvious to the user when something goes wrong. Picasso assists you with easy to call functions, which provide the things you need to have a better app.

But we’re not done with our optimization yet. Next week, we’ll look at image resizing, scaling and a wonderful function named .fit() .

Not an Expert Yet? Get Our Picasso Book!

Nowadays apps need to be polished to be successful. Picasso offers an easy way to add images to your app without much hassle.

Learn how to create image-rich Android apps with our book on Picasso. You’ll quickly know how handle images in your Android apps. Your users will thank you for this small investment in the app experience.

Improve your app today and enjoy working with images on Android.

Get Notified on New Future Studio
Content and Platform Updates

Get your weekly push notification about new and trending
Future Studio content and recent platform enhancements

Источник

Picasso

A powerful image downloading and caching library for Android

Introduction

Images add much-needed context and visual flair to Android applications. Picasso allows for hassle-free image loading in your application—often in one line of code!

Many common pitfalls of image loading on Android are handled automatically by Picasso:

  • Handling ImageView recycling and download cancelation in an adapter.
  • Complex image transformations with minimal memory use.
  • Automatic memory and disk caching.

Features

Adapter Downloads

Adapter re-use is automatically detected and the previous download canceled.

Image Transformations

Transform images to better fit into layouts and to reduce memory size.

You can also specify custom transformations for more advanced effects.

Pass an instance of this class to the transform method.

Place Holders

Picasso supports both download and error placeholders as optional features.

A request will be retried three times before the error placeholder is shown.

Resource Loading

Resources, assets, files, content providers are all supported as image sources.

Debug Indicators

For development you can enable the display of a colored ribbon which indicates the image source. Call setIndicatorsEnabled(true) on the Picasso instance.

Download

The source code to the Picasso, its samples, and this website is available on GitHub.

Maven

Gradle

Contributing

If you would like to contribute code you can do so through GitHub by forking the repository and sending a pull request.

When submitting code, please make every effort to follow existing conventions and style in order to keep the code as readable as possible. Please also make sure your code compiles by running mvn clean verify .

Before your code can be accepted into the project you must also sign the Individual Contributor License Agreement (CLA).

Источник

Читайте также:  Взломщик паролей вай фая для андроид
Оцените статью