EzDev.org

glide

glide - An image loading and caching library for Android focused on smooth scrolling Glide v4 : Fast and efficient image loading for Android fast and efficient image loading for android


Glide: load specified region of image

I am loading image from server using Glide with this code:

private void loadImage(Context context, String url, ImageView imageView, int x1, int y1, int x2, int y2) {
    Glide.with(context)
       .load(url)
       .into(imageView);
}

I need to show only piece of image in my ImageView. Coordinates of this piece placed in variables x1, x2, y1 and y2. How to cut only needed part of image using Glide?


Source: (StackOverflow)

Glide can't load file from internal storage

I have an Activity in which I download a zipfile of images and then unzip in the getFilesDir(). Path is like this :

/data/user/0/packagename/files/files/example.png

When I try to load these images however, they're not showing. I'm using this code to get the path and load the image:

   String loc = getFilesDir().getPath() + "/" + Config.IMAGES_LOCATION +"/";
   String imageloc = loc + model.getThumbnail();
   Glide.with(ActivityImageGallery.this).load(imageloc).into(image);

The imageloc path is the same as the save location and when creating a file from the path, it shows that it would exist.

I tried using file:// in front of the path, but that doesn't work either. WRITE_EXTERNAL en READ_EXTERNAL permissions are asked and granted.


Source: (StackOverflow)

Can't set wallpaper from a bunch of URLs (string array). How to solve this?

I'm currently making an app that displays images from the web in a grid layout(recyclerView). When one image is selected another activity is opened and displays the same image in fullscreen(just like an image gallery). I'm using Glide library for this purpose. In this activity I have implemented a bottom toolbar which contains two items "set wallpaper" and "Download". I have written the code to set the wallpaper but it does not seem to work and the app never crashes too. I have attached the image of the grid view and the other activity(code and fullscreen image) I need helping in setting the full screen image as wallpaper and this applies for all the images in grid view. Images : http://imgur.com/a/LSbX0

Code :

public class SecondActivity extends Activity {

    BottomBar bottomBar;

    public static final String image = "SecondActivity.LIST_ITEMS";
    ImageView selectedImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);


        bottomBar = (BottomBar)findViewById(R.id.bottom_navbar);

        selectedImage = (ImageView) findViewById(R.id.selectedImage); // init a ImageView

        final ListItem listItem = getIntent().getParcelableExtra(image);

        Glide.with(this).asBitmap().load(listItem.getImgurl()).into((ImageView)findViewById(R.id.selectedImage));



        bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
           public void onTabSelected(@IdRes int tabId) {
               if(tabId == R.id.setwallpaper){


                   Glide.with(getApplicationContext()).asBitmap().load(selectedImage).into(new SimpleTarget<Bitmap>(){

                        @Override
                        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                            try {
                                WallpaperManager.getInstance(getApplicationContext()).setBitmap(resource);
                                Toast.makeText(getApplicationContext(), "Success",Toast.LENGTH_LONG).show();


                            } catch (IOException e) {
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Failed",Toast.LENGTH_LONG).show();
                            }
                        }



                   });
               }

               if(tabId == R.id.download){





               }

            }
        });



    }
}

log :

08-27 23:28:08.881 1309-1329/? D/AudioFlinger: mixer(0xa8083940) throttle end: throttle time(22)
08-27 23:28:08.884 5247-5403/quote.quotemania E/GlideExecutor: Request threw uncaught throwable
    com.bumptech.glide.Registry$NoModelLoaderAvailableException: Failed to find any ModelLoaders for model: android.widget.ImageView{b8534d9 V.ED..... ......I. 0,0-0,0 #7f0f00a7 app:id/selectedImage}
      at com.bumptech.glide.Registry.getModelLoaders(Registry.java:227)
      at com.bumptech.glide.load.engine.DecodeHelper.getLoadData(DecodeHelper.java:179)
      at com.bumptech.glide.load.engine.DecodeHelper.getCacheKeys(DecodeHelper.java:197)
      at com.bumptech.glide.load.engine.ResourceCacheGenerator.startNext(ResourceCacheGenerator.java:41)
      at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:282)
      at com.bumptech.glide.load.engine.DecodeJob.runWrapped(DecodeJob.java:249)
      at com.bumptech.glide.load.engine.DecodeJob.run(DecodeJob.java:222)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
      at java.lang.Thread.run(Thread.java:761)
      at com.bumptech.glide.load.engine.executor.GlideExecutor$DefaultThreadFactory$1.run(GlideExecutor.java:347)
08-27 23:28:08.888 5247-5273/quote.quotemania V/FA: Using measurement service
08-27 23:28:08.888 5247-5273/quote.quotemania V/FA: Connection attempt already in progress
08-27 23:28:08.889 5247-5273/quote.quotemania V/FA: Using measurement service
08-27 23:28:08.889 5247-5273/quote.quotemania V/FA: Connection attempt already in progress
08-27 23:28:08.889 5247-5273/quote.quotemania V/FA: Activity resumed, time: 3119251
08-27 23:28:08.890 5247-5273/quote.quotemania D/FA: Connected to remote service
08-27 23:28:08.890 5247-5273/quote.quotemania V/FA: Processing queued up service tasks: 3
08-27 23:28:08.891 5247-5247/quote.quotemania W/Glide: Load failed for android.widget.ImageView{b8534d9 V.ED..... ......I. 0,0-0,0 #7f0f00a7 app:id/selectedImage} with size [-2147483648x-2147483648]
                                                       class com.bumptech.glide.load.engine.GlideException: Failed to load resource
08-27 23:28:08.891 5247-5247/quote.quotemania E/Glide: class com.bumptech.glide.load.engine.GlideException: Failed to load resource
08-27 23:28:08.900 2431-5278/com.google.android.gms V/FA-SVC: Logging event: origin=auto,name=_e,params=Bundle[mParcelledData.dataSize=132]
08-27 23:28:08.906 2431-5278/com.google.android.gms V/FA-SVC: Saving event, name, data size: _e, 68
08-27 23:28:08.906 2431-5278/com.google.android.gms V/FA-SVC: Event recorded: Event{appId='quote.quotemania', name='_e', params=Bundle[{_o=auto, _et=8878, _sc=BrowseQuotes, _si=-5888889340355970828}]}
08-27 23:28:08.909 2431-5278/com.google.android.gms V/FA-SVC: Background event processing time, ms: 9
08-27 23:28:08.938 1298-1340/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer
08-27 23:28:08.955 1298-1340/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer
08-27 23:28:08.967 1298-1340/? D/gralloc_ranchu: gralloc_alloc: format 1 and usage 0x900 imply creation of host color buffer
08-27 23:28:08.984 5247-5247/quote.quotemania W/View: requestLayout() improperly called by android.widget.TextView{8a7a611 V.ED..... ......ID 294,133-294,196 #7f0f00ae app:id/bb_bottom_bar_title} during layout: running second layout pass
08-27 23:28:08.984 5247-5247/quote.quotemania W/View: requestLayout() improperly called by android.widget.TextView{6211376 V.ED..... ......ID 294,140-294,196 #7f0f00ae app:id/bb_bottom_bar_title} during layout: running second layout pass
08-27 23:28:09.127 1577-1600/system_process I/ActivityManager: Displayed quote.quotemania/.SecondActivity: +279ms
08-27 23:28:13.903 5247-5273/quote.quotemania V/FA: Inactivity, disconnecting from the service
08-27 23:28:19.770 1309-1329/? D/AudioFlinger: mixer(0xa8083940) throttle end: throttle time(11)
08-27 23:28:21.668 1309-1329/? D/AudioFlinger: mixer(0xa8083940) throttle end: throttle time(43)
08-27 23:28:21.732 1309-1329/? D/AudioFlinger: mixer(0xa8083940) throttle end: throttle time(1)
08-27 23:28:24.034 1309-1329/? D/AudioFlinger: mixer(0xa8083940) throttle end: throttle time(1)

Android manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="quote.quotemania">

<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"></activity>
    <activity android:name=".BrowseQuotes"></activity>
    <activity android:name=".splash_screen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".SecondActivity"></activity>
</application>

xml file :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:design="http://schemas.android.com/apk/res-auto"

android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/framelayout"
    android:layout_above="@+id/bottom_navbar" >


<ImageView
    android:id="@+id/selectedImage"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="fitXY" />

</FrameLayout>

<com.roughike.bottombar.BottomBar
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:id="@+id/bottom_navbar"
    android:layout_alignParentBottom="true"
    app:bb_tabXmlResource="@xml/bottombar_tabs"
    android:background="#263f40"
    app:bb_inActiveTabColor="#fff"
    app:bb_activeTabColor="#fff"
    >

</com.roughike.bottombar.BottomBar>

</RelativeLayout>

Source: (StackOverflow)

Image flickering when Glide loads it

I have a list of image views and some of them will be frequently updated with a fixed url. By appending a timestamp query parameter in the end of the url. It works, but I found when it updates it will also clear the current content. Any way to prevent this?

// the one needed to update with timestamp appended
image += "?"+String.valueOf(System.currentTimeMillis());
Glide.with(mContext.getApplicationContext())
        .load(image)
        .error(R.drawable.default_avatar)
        .centerCrop()
        .crossFade()
        .into(((VideoViewHolder) holder).img);

// the others don't need to update
Glide.with(mContext.getApplicationContext())
        .load(image)
        .error(R.drawable.default_avatar)
        .centerCrop()
        .crossFade()
        .into(((VideoViewHolder) holder).img);

Note that the others without timestamp appended are all good.


Source: (StackOverflow)

Glide Library Loading Very Slow with GIF

I'm using Glide library to load GIF files into my app. Here is what I implemented:

Glide.with(context)
     .load(stringImage)
     .asGif()
     .diskCacheStrategy(DiskCacheStrategy.SOURCE)
     .into(postImage);

But for some reason the GIF files are loading with very slow frame. I tried to Google but I wasn't able to figure it out. Any help is appreciated.


Source: (StackOverflow)

Loading Images with Glide and FirebaseUI in newest Firebase Version (10.2.4)

So I updated firebase to the newest version (10.2.4) alongside playservices, and suddenly all the images in my app loaded with Glide are no longer loading. If I have this in my build.gradle

ext {
    supportLibraryVersion = '25.3.1'
    firebaseLibraryVersion = '10.2.1'
    playServicesLibraryVersion = '10.2.1'
}

dependencies {
    // play services
    compile "com.google.android.gms:play-services-places:$playServicesLibraryVersion"
    compile "com.google.android.gms:play-services-auth:$playServicesLibraryVersion"
    // firebase
    compile "com.google.firebase:firebase-storage:$firebaseLibraryVersion"
    // ...
}

Running this line of Code Works Fine.

Glide.with(mContext).using(new FirebaseImageLoader()).load(storageReference).into(viewHolder.profileImage);

However, if I set firebase and play services to the newest version:

ext {
    supportLibraryVersion = '25.3.1'
    firebaseLibraryVersion = '10.2.4'
    playServicesLibraryVersion = '10.2.4'
}

Then the line above doesn't work anymore. It simply doesn't load the Image. I changed the code to this so I could look at what the error could be:

    Glide.with(mContext)
            .using(new FirebaseImageLoader())
            .load(storageReference)
            .listener(new RequestListener<StorageReference, GlideDrawable>() {
        @Override
        public boolean onException(Exception e, StorageReference model, Target<GlideDrawable> target, boolean isFirstResource) {
            Log.d(TAG, "exception " + e.getMessage());
            e.printStackTrace();
            return false;
        }

        @Override
        public boolean onResourceReady(GlideDrawable resource, StorageReference model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
            return false;
        }
    }).into(viewHolder.mProfileImage);

I get this Log Statement:

Could not open resulting stream.

and this Exception:

  W/System.err: java.io.IOException: Could not open resulting stream.
05-08 19:10:04.513 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.google.firebase.storage.StreamDownloadTask.zzacI(Unknown Source)
05-08 19:10:04.513 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.google.firebase.storage.StreamDownloadTask.zza(Unknown Source)
05-08 19:10:04.513 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.google.firebase.storage.StreamDownloadTask$1.zzacK(Unknown Source)
05-08 19:10:04.513 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.google.firebase.storage.StreamDownloadTask$1.call(Unknown Source)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.google.firebase.storage.StreamDownloadTask$zza.zzacM(Unknown Source)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.google.firebase.storage.StreamDownloadTask$zza.read(Unknown Source)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at java.io.BufferedInputStream.read(BufferedInputStream.java:290)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.resource.bitmap.RecyclableBufferedInputStream.fillbuf(RecyclableBufferedInputStream.java:166)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.resource.bitmap.RecyclableBufferedInputStream.read(RecyclableBufferedInputStream.java:229)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$StreamReader.getUInt16(ImageHeaderParser.java:334)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.resource.bitmap.ImageHeaderParser.getType(ImageHeaderParser.java:87)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder$ImageTypeParser.parse(GifBitmapWrapperResourceDecoder.java:147)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decodeStream(GifBitmapWrapperResourceDecoder.java:82)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decode(GifBitmapWrapperResourceDecoder.java:71)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decode(GifBitmapWrapperResourceDecoder.java:61)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.resource.gifbitmap.GifBitmapWrapperResourceDecoder.decode(GifBitmapWrapperResourceDecoder.java:22)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.engine.DecodeJob.decodeFromSourceData(DecodeJob.java:190)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.engine.DecodeJob.decodeSource(DecodeJob.java:177)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.engine.DecodeJob.decodeFromSource(DecodeJob.java:128)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.engine.EngineRunnable.decodeFromSource(EngineRunnable.java:122)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.engine.EngineRunnable.decode(EngineRunnable.java:101)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.engine.EngineRunnable.run(EngineRunnable.java:58)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at java.lang.Thread.run(Thread.java:818)
05-08 19:10:04.514 8839-8839/com.gmail.linxydev.clientapp W/System.err:     at com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor$DefaultThreadFactory$1.run(FifoPriorityThreadPoolExecutor.java:118)

Going back to version 10.2.1 fixes the problems, however maybe there is another fix? I tested this on 2 devices, one running android 6 and the other running 7, and it happened on both.


Source: (StackOverflow)

How to set timeout with Okhttp3 and GlideV4?

Am using glide v4 and okhttp3 integration with glide. I want to change it's timeout time. how to do that? by extending AppGlideModule or is there any other way? I have searched for proper documentation but not seen anywhere.


Source: (StackOverflow)

Splash screen with glide issue as it is not working

I am trying to make a splash screen which is using glide library but even after trying many times i am unable to start the splash screen. Do i have to use Async task and how will i start an activity just after the splash screen. I have used

com.master.android:glideimageview:1.0 and com.github.bumptech.glide:glide:4.0.0-RC1 in my build.gradle(module) Please , guide me ?

Here is my code:

splash.xml

<?xml version="1.0" encoding="utf-8"?>
 <android.support.constraint.ConstraintLayout 
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:layout_width="match_parent"
 android:layout_height="match_parent">

 <ImageView
    android:contentDescription="@string/splash_bg_cd"
    android:id="@+id/splash_bg"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_width="0dp"
    android:layout_height="0dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="@string/text_splash"
    android:textSize="@dimen/splash_text_size"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>

and Java Code Splash.java

import com.bumptech.glide.Glide;
import com.master.glideimageview.*;

public class Splash extends AppCompatActivity {

    private ImageView ivBgSplash;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable 
        PersistableBundle persistentState) {

        super.onCreate(savedInstanceState, persistentState);

        setContentView(R.layout.splash_screen);

        initViews();
     }

     private void initViews() {

        ivBgSplash = (ImageView) findViewById(R.id.splash_bg);
        Glide.with(this)
                .load(R.drawable.hlb_logo)
                .into(ivBgSplash);
        AnimationDrawable splashAnimation = (AnimationDrawable) 
        ivBgSplash.getBackground();
        splashAnimation.start();
     }
}

Source: (StackOverflow)

MINGW64 "make build" error: "bash: make: command not found"

I am working on Windows 10. I want to run a "make build" in MINGW64 but following error comes up:

$ make build
bash: make: command not found

I want to build Glide for Golang

I tried following:

$ sudo yum install build-essential
bash: sudo: command not found

As well as:

$ yum install build-essential
bash: yum: command not found

And:

$ apt-cyg build-essential
bash: apt-cyg: command not found

How can I "work-around" this problem?


Source: (StackOverflow)

Glide, Clear cache when cache size is larger than 50 mb

I am using Glide library for image loading. There is lot of images in my app so I want to clear cache once cache size is larger than 50 mb. Can someone help me to do so?


Source: (StackOverflow)

How set image into ImageView using Glide and a URI?

I'm trying to display an image in a ImageView using Glide library, the image is in res > drawable folder, and its name retrived from a db. How can I get a resource using an Uri?, redWifi.getImagen() returns a string like "imagename.png".

I'm using the next code but doesn't show the image.

Glide.with(detallesRedGuardadaActivity.this)
                .load(Uri.parse("file:///android_asset/" + redWifi.getImagen()))
                .asBitmap()
                .into(iconoRed);

I tried with .load(Uri.parse("file://android_asset/" + redWifi.getImagen())) but still not working.


Source: (StackOverflow)

How to load only part of image with Glide from Firebase?

I have imageview, which should show only part of image (part which fits into part of screen). After user click, it will open whole image. But I canĀ“t figure out, how to load only part of image into imageview. Problem is that Glide fits image into imageview, always.

Glide.with(context)
     .using(new FirebaseImageLoader())
     .load(storageReference)
     .into(imageView);

How it is looks now. Red part is ImageView.

How it is working now

How I wish to have it.

How I would like to have it

EDIT

Following code will fits, but it show whole image, only only part of it and it destroy proportions.

android:scaleType="fitXY"
android:adjustViewBounds="true"

enter image description here


Source: (StackOverflow)

Android memory leak glide

I have an activity which loads pictures in ImageViews with glide. Here is a sample of my glide code : Glide.with(ImageVOne.getContext()) .load(geoInfo.getPhotoUrl1()) .skipMemoryCache(true) .priority(Priority.NORMAL) .into(ImageVOne); I load from 1 to 35 pictures, each picture should be between 150ko & 250ko. I cannot reduce that.

This activity can be accessed several times in a session from the main activity, and each time it loads different pictures. For example the first time it will be pictures of Washington, then pictures of London etc

My issue is that the use of memory increases a lot every time the activity that loads the pictures is started : enter image description here

I can start the activity from 3 to 5 times, then the app crashes. The error message is java.lang.OutOfMemoryError: Failed to allocate a 1411340 byte allocation with 1126320 free bytes and 1099KB until OOM

I read posts about memory leaks but I thought Glide would avoid this issue. My activity with the pictures is finished before another one is started, but the memory allocated to my app do not seem to drop. I also added android:noHistory="true" to my picture activity in the Manifest but it doesn't change anything.

I added android:largeHeap="true" in my Manifest but it just postpone my issue (I can start the pictures activity about 10 to 15 times) and I get a lot of pictures not loaded in my imageviews before the app crashes, so its not a good solution for me.

I also tried to add .skipMemoryCache(true) when I use glide but I don't notice any change.

I guess my "memory use" should decrease every time I go from the pictures activity to the main activity, then increase when I start my pictures activity again with new pictures. But from what I see on the blue graph it almost only increases. Do you see what I should do ?

Thank you,

Alex


Source: (StackOverflow)

OutOfMemory error on Continues swipe of Viewpager that has used Glide to load bitmaps into it

I am trying to develop an image gallery application. The Error occurs in the page mentioned. When my page loads I have an Image View within a ViewPager and a horizontal strip at the bottom where I have used recycler view.On load

The first image loads on the ViewPager's imageview and the corresponding images thumbnail gets highlighted on the horizontal strip. When clicking on a thumbnail at bottom horizontal strip, the corresponding image loads on the Viewpager's image view. All my functionalities are working as desired. But when I continuously swipe the viewpager even after giving large heap for my application the app becomes unresponsive/crashes. From the log and Android Monitors Memory graph I could clearly make out that its a OOM error. Now comes the key factor I have used Glide to load images into the image view of viewpager. To make sure Glide frees up the bitmap it uses I have used the following methods:

Glide
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)

I have also called,

  Glide.get(context).clearMemory();
        AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            //TODO your background code
            Glide.get(context).clearDiskCache();
        }
    });

within destroyItem method of View pager.

Also, I have used the following glide code to load bitmap image into image view:

Glide
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
     mediaDetails.get(curPos).getFullImageView().setImageBitmap(resource);
                         }
      }

I need a bitmap resource since I have implemented Zoom and Pan functionalities on the image view. What will be the most effective way to free up the bitmap created when the view pagers view get destroyed. Or is there any other way to handle this issue? Your help would be most valuable.


Source: (StackOverflow)

How to add listener correctly to glide

I am using glide for displaying album art but somehow I am not able to display it. I want to add listener to glide for locating errors but its not working. It shows error saying :

listener(com.bumptech.glide.request.RequestListener) in com.bumptech.glide.DrawableRequestBuilder cannot be applied to (anonymous com.bumptech.glide.request.RequestListener)

PlayListActivity.java :

package com.example.dell_1.myapp3;


import android.app.Activity;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;


public class PlayListActivity extends Activity {

    private String[] mAudioPath;
    private MediaPlayer mMediaPlayer;
    private String[] mMusicList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_list);

        mMediaPlayer = new MediaPlayer();
        ListView mListView = (ListView) findViewById(R.id.list);

        mMusicList = getAudioList();

        ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, mMusicList);
        mListView.setAdapter(mAdapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                                    long arg3) {

                try {
                    playSong(mAudioPath[arg2]);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private String[] getAudioList() {
        final Cursor mCursor = getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA}, null, null,
                "LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");

        int count = mCursor.getCount();

        String[] songs = new String[count];
        mAudioPath = new String[count];
        int i = 0;
        if (mCursor.moveToFirst()) {
            do {
                songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
                mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                i++;
            } while (mCursor.moveToNext());
        }

        mCursor.close();

        return songs;
    }

    private void playSong(String path) throws IllegalArgumentException,
            IllegalStateException, IOException {

        setContentView(R.layout.activity_android_building_music_player);
        Log.d("ringtone", "playSong :: " + path);

        mMediaPlayer.reset();
        mMediaPlayer.setDataSource(path);
//mMediaPlayer.setLooping(true);
        mMediaPlayer.prepare();
        mMediaPlayer.start();

        asd();
    }

    public void asd(){
        File music = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
// Tested with music from Windows 7's c:\Users\Public\Music\Sample Music
        String mAudioPath = new File(music, "Maid with the Flaxen Hair.mp3").getAbsolutePath();
        ImageView imageView = (ImageView) findViewById(R.id.coverart);
        Glide
                .with(this)
                .load(new AudioCover(mAudioPath))
                .placeholder(R.drawable.adele1)
                .error(R.drawable.adele1)
                .listener(new RequestListener<Uri, GlideDrawable>() {
                    @Override public boolean onException(Exception e, Uri model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }
                    @Override public boolean onResourceReady(GlideDrawable resource, Uri model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        // easy
                        return false;
                        // impossible?
                    }
                })
                .into(imageView)
        ;
    }
}

AudioCover.java :

package com.example.dell_1.myapp3;

import android.content.Context;
import android.media.MediaMetadataRetriever;

import com.bumptech.glide.*;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.GenericLoaderFactory;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;
import com.bumptech.glide.load.model.stream.StreamModelLoader;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class AudioCover {
    final String path;
    public AudioCover(String path) {
        this.path = path;
    }
}

class AudioCoverLoader implements StreamModelLoader<AudioCover> {
    @Override public DataFetcher<InputStream> getResourceFetcher(AudioCover model, int width, int height) {
        return new AudioCoverFetcher(model);
    }

    static class Factory implements ModelLoaderFactory<AudioCover, InputStream> {
        @Override public ModelLoader<AudioCover, InputStream> build(Context context, GenericLoaderFactory factories) {
            return new AudioCoverLoader();
        }
        @Override public void teardown() {
        }
    }
}
class AudioCoverFetcher implements DataFetcher<InputStream> {
    private final AudioCover model;
    private FileInputStream stream;

    public AudioCoverFetcher(AudioCover model) {
        this.model = model;
    }

    @Override public String getId() {
        return model.path;
    }

    @Override public InputStream loadData(Priority priority) throws Exception {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(model.path);
            byte[] picture = retriever.getEmbeddedPicture();
            if (picture != null) {
                return new ByteArrayInputStream(picture);
            } else {
                return fallback(model.path);
            }
        } finally {
            retriever.release();
        }
    }

    private static final String[] FALLBACKS = {"cover.jpg", "album.jpg", "folder.jpg"};
    private InputStream fallback(String path) throws FileNotFoundException {
        File parent = new File(path).getParentFile();
        for (String fallback : FALLBACKS) {
            // TODO make it smarter by enumerating folder contents and filtering for files
            // example algorithm for that: http://askubuntu.com/questions/123612/how-do-i-set-album-artwork
            File cover = new File(parent, fallback);
            if (cover.exists()) {
                return stream = new FileInputStream(cover);
            }
        }
        return null;
    }

    @Override public void cleanup() {
        // already cleaned up in loadData and ByteArrayInputStream will be GC'd
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException ignore) {
                // can't do much about it
            }
        }
    }
    @Override public void cancel() {
        // cannot cancel
    }
}

Source: (StackOverflow)