当前位置: 动力学知识库 > 问答 > 编程问答 >

Android Handling changing of orientation. app crash points on changing image using glide

问题描述:

Details:

I am changing image from drawable using Glide. When I changed orientation into landscape it gives me a logcat error pointing to method I use for changing my image with Glide.

Code snippet:

private void changeDice1(int drawable) {

Glide.with(MainActivity.this)

.load(drawable)

.crossFade()

.diskCacheStrategy(DiskCacheStrategy.SOURCE)

.into(ivDice1);

}

@Override

public void onDestroy() {

super.onDestroy();

}

Logcat error:

网友答案:

The Glide loads image asynchronously. So if you change the orientation of your device, it may happen that, the reference context is changed and an exception is thrown. So modify your function like this using a try-catch block.

private void changeDice1(int drawable) {
    try{
        Glide.with(MainActivity.this)
                .load(drawable)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(ivDice1);
    } catch(Exception e) { e.printStackTrace();}
}

Now call the function again in onConfigurationChanged.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    changeDice1(R.drawable.your_image);
}
网友答案:

You can use Glide.clear() to cancel a load.

However, that exception occurs when you try to start a new load after your activity has been destroyed. Are you starting to load images after fetching some data asynchronously? If so you probably want to cancel your async fetch when your activity is stopped or at least ignore the result if the fetch finishes and your activity is destroyed.

see this issue for more information: https://github.com/bumptech/glide/issues/975

分享给朋友:
您可能感兴趣的文章:
随机阅读: