2011-09-21 201 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(無例外)