2011-09-21 71 views
8

我似乎无法弄清楚这一点。我有2个具有不同特征的java类,每个调用BitmapFactory.decodeResource获取相同的图像资源,一个返回位图,另一个返回null。两个类都在同一个包中。Android:BitmapFactory.decodeResource返回null

这里是工作的类,它调用返回位图的BitmapFactory.decodeResource。我只包含相关的代码。

package advoworks.test; 

import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Canvas; 
import android.graphics.Rect; 
import android.util.Log; 
import android.view.Surface; 
import android.view.SurfaceHolder; 
import android.view.SurfaceView; 

public class MainScreen extends SurfaceView implements SurfaceHolder.Callback { 

private static final String TAG = MainScreen.class.getSimpleName(); 

public MainScreen(Context context) { 
    super(context); 

    Bitmap bitmap; 
    bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.droid_1); 

    //adding the callback (this) to the surface holder to intercept events; 
    getHolder().addCallback(this); 

    // make the GamePanel focusable so it can handle events 
    setFocusable(true); 

} 
} 

这是不起作用的类。 BitmapFactory.decodeResource在调试中返回NULL。我只包含了我认为相关的代码。

package advoworks.test; 
import android.content.res.Resources; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Canvas; 
import android.util.Log; 

public class Segment { 

private int x; 
private int y; 
private Bitmap bitmap; 

public Segment(int x, int y) { 
    Log.d(TAG, "Creating Segment"); 
    try { 
     this.bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.droid_1); 
    } catch (Exception e) { 
     Log.d(TAG,"Error is " + e); 
    } 
    this.x = x; 
    this.y = y; 
    Log.d(TAG, "Created Segment"); 
} 
} 

任何线索的人?

+0

你得到的logcat的任何错误? – blessenm

+0

不,我没有得到任何错误logcat :( – Kevin

+0

为什么你需要加载相同的资源两次在同一个应用程序。加载一次,并通过其引用到所有地方,你需要它 – Ronnie

回答

3

getResources()是一个Context类方法,并且您没有在Segment类中使用上下文。它是如何工作的。您应该致电getApplicationContext().getResources()

您应该将上下文传递给Segment构造函数。

public Segment(Context context, int x, int y) { 
    .... 
    bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.droid_1); 
    .... 
} 
+0

感谢您的答复,可以你解释一下“Context class method”是什么意思?我找不到google上的定义 – Kevin

+0

'getResources()'是'Context'类的成员,因此需要上下文对象来调用这个方法 – Ronnie

+0

为什么不getResources导致编译错误然后呢? 无论如何,我已经试过这样做: – Kevin

3

检查图像的分辨率,如果过大,BitmapFactory.decodeResource只会返回null(无例外)