Android的背景下NullPointerException异常 [英] android context nullpointerexception

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

问题描述

我有Android的上下文一个小问题,我不知道如何解决problem.Here是code我使用的:

I have a little issue with android Context and I don't know how to solve the problem.Here is the code I am using :

public class TestActivity {
Context context;
public static  String getPackageVersion(){  
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            version = packageInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

    public static boolean checkClientApiVer(String clientApiVer){

        int s = RPCCommunicator.strVerToIntVer(clientApiVer);
        int c = RPCCommunicator.strVerToIntVer(getPackageVersion());

        return (c>=s);
    }

     public boolean execute() {

        serverApiVer = jsonObj.getString("server_api_ver");
        Log.w("SERVER API VER","SHOW SERVER API VERSION : "+serverApiVer);

            checkClientApiVer(serverApiVer);
}

}

和它说,空指针异常在这一行:

and it says Nullpointer exception in this line :

PackageManager pm = context.getPackageManager();

其实我不能使用 this.getPackageManager() TestActivity.getPackageManager()可以和我T设置背景这个

有什么建议?

推荐答案

如果你的类是一个活动,它是更好地使用这个作为背景。如果在其他类需要一个环境,你可以有一个单指针在您的applicationContext。

If your class is an activity, it's better to use this as a context. If you need a context in another class, you can have a singleton pointer on your applicationContext.

public class MyApp extends Application {

    private static MyApp instance;

    public MyApp() {
        instance = this;
    }

    public static Context getContext() {
        return instance;
    }
}

和在你的清单文件:

<application
    android:name="com.mycompany.appname.MyApp"
    android:icon="@drawable/icon"
    android:label="@string/app_name">

现在你可以总是有一个上下文

Now you can always have a context with

MyApp.GetContext();

这篇关于Android的背景下NullPointerException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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