【发布时间】:2017-08-04 20:58:44
【问题描述】:
我一直在试图弄清楚为什么位图在 SimpleTarget 内给了我一个大小值,但在 SimpleTarget 之外就为空。
private Bitmap getImage(String path){
final Bitmap[] bitmaps = new Bitmap[1];
Glide.with(getApplicationContext())
.load(path)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
bitmaps[0] = resource;
Log.v(TAG, "bitmap: " + bitmaps[0].getByteCount());// Returns a value as expected.
}
});
Log.v(TAG, "bitmap2: " + bitmaps[0].getByteCount());// throws a null object reference.
return bitmaps[0];
}
编辑:AsyncTask 方法。
私有位图getImage(字符串路径){
final Bitmap[] bitmaps = new Bitmap[1];
new AsyncTask<Void, Void, Void>() {
Bitmap tmp;
@Override
protected Void doInBackground(Void... params) {
try {
tmp = Glide.with(getApplicationContext())
.load("http://i.annihil.us/u/prod/marvel/i/mg/b/40/image_not_available.jpg")
.asBitmap()
.into(-1,-1)
.get();
} catch (final ExecutionException | InterruptedException e) {
Log.e(TAG, e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(Void dummy) {
if (null != tmp) {
// The full bitmap should be available here
bitmaps[0] = tmp;
Log.v(TAG, "bitmap: " + bitmaps[0].getHeight());
Log.d(TAG, "Image loaded");
};
}
}.execute();
Log.v(TAG, "bitmap2: " + bitmaps[0].getHeight());// throws a null object reference.
return bitmaps[0];
}
编辑:添加了与问题相关的日志。
08-04 19:35:03.687 5183-5183/com.example.comics V/com.example.comics.MainActivity: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getHeight()' on a null object reference
08-04 19:35:03.709 5183-5183/com.example.comics V/com.example.comics.backend.services.BackgroundService: bitmap: 537
编辑:如果位图未定义为最终的,它会喊出从内部类访问。声明为 final。
【问题讨论】:
标签: android bitmap android-glide