Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android context nullpointerexception

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

Actually I can't use this.getPackageManager(), or TestActivity.getPackageManager() and I can't set context to this.

Any suggestions?

like image 549
Android-Droid Avatar asked Mar 10 '26 17:03

Android-Droid


1 Answers

@Roflcoptr pointed out the basic, but actually, your class doesn't extend activity, so it is not a context, change it to:

public class TestActivity extends Activity

if you want it to be an actual activity, or, if it should be only a helper class, pass it the activity when it is instantiated.

like image 77
MByD Avatar answered Mar 14 '26 03:03

MByD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!