1

I have 2 classes, from class BinderData, which extends BaseAdapter (I can't extend this class to Activity as I have to extend to BaseAdapter) I am calling class AssetActivity by following code:

AssetActivity a = new AssetActivity();
Drawable image=a.getImage(imageUri);

Here imageuri is a string and it is populated properly.In the AssetActivity class following code I am using.

public class AssetActivity extends Activity {
    private static final String TAG = "AssetActivity";

    public Drawable getImage(String imgName) {

        String nextImageName = imgName+ ".jpg";
        AssetManager assets = getAssets(); // get app's AssetManager
        InputStream stream; // used to read in Image images     
        Drawable flag=null;
        try {
            // get an InputStream to the asset representing the next Image
            stream = assets.open(nextImageName );

            // load the asset as a Drawable and display on the objImageView
             flag = Drawable.createFromStream(stream, nextImageName);
        } // end try
        catch (IOException e) {
            Log.e(TAG, "Error loading " + nextImageName, e);
        } // end catch
        return flag;
    }
} 

When I am running the code I am getting NullPointerException at following line.

AssetManager assets = getAssets();

There are assets at the asset folder and I am able to fetch them in some other class which explicitly calls getAssets() method and that class extends Activity. Please help me with this. I am suspecting that I am doing something wrong in calling getImage method in BinderData class. Please help me. Thanks.

4

1 回答 1

4

AssetManager assets = getAssets();会给你NullPointerException因为getAssets()会回报nullgetAssets()需要在Activity中调用Context

您不允许为类创建对象,android 将通过生命周期方法来处理它。所以不要为Activity创建对象。

将该方法放在您的 Activity 类context.getAssets()中,用于获取资产

于 2013-05-15T17:48:59.693 回答