Android assetManager getAsset() 抛出 nullPointer 异常 [英] Android assetManager getAsset() throwing nullPointer exception

查看:67
本文介绍了Android assetManager getAsset() 抛出 nullPointer 异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个类,来自 BinderData 类,它扩展了 BaseAdapter(我无法将此类扩展到 Activity,因为我必须扩展到 BaseAdapter)我正在通过以下代码调用 AssetActivity 类:

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);

这里的 imageuri 是一个字符串,它被正确填充.在 AssetActivity 类中,我正在使用以下代码.

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;
    }
} 

当我运行代码时,我在下一行收到 NullPointerException.

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

AssetManager assets = getAssets();

资产文件夹中有资产,我可以在其他一些显式调用 getAssets() 方法的类中获取它们,并且该类扩展了 Activity.请帮我解决一下这个.我怀疑我在 BinderData 类中调用 getImage 方法时做错了什么.请帮我.谢谢.

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.

推荐答案

AssetManager assets = getAssets(); 会给你 NullPointerException 因为 getAssets() 将返回 null.getAssets() 需要在Activity中调用Context;

AssetManager assets = getAssets(); will give you NullPointerException because getAssets() will return null. getAssets() needs to be called in the Activity Context;

您不能为类创建对象,android 将通过生命周期方法处理.所以不要为 Activity 创建对象.

You are not allowed to create Object for the class android will take care of that through life cycle methods. So don't create Object for Activity.

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

place that method in your Activity class use context.getAssets() to get the Assets

这篇关于Android assetManager getAsset() 抛出 nullPointer 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆