android – Trying to get Package Version Information to display in an "About" message-ThrowExceptions

Exception or error:

I have been struggling with getting the versionName for a running application from the PackageInfo Object type.

I have constructed a Parcelable Interface with all of the fields associated with the PackageInfo Object type. The primary input for that interface method is a Parcel object.

I cannot seem to figure out how to correctly associate these Parcelable, Parcel, and PackageInfo objects.

Is there any sample code out there that I can look at? Doesn’t seem like it should be that difficult but it seems to be stumping me.


How to solve:

Sample code:

try {
    PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    return packageInfo.versionName;
} catch (NameNotFoundException e) {
    //Handle exception


Modern way:

If you build your Android project by Gradle (with Android Studio), there is a best shortcut to get version:


It’s linked to versionName in your build.gradle file.

In fact, you can get Application ID, and more information from your build.gradle file by this way.


I use the following code to get the version used in the manifest. I wrote a small function to encapsulate and hide this somewhat big chunk needed to just get an int.

private int getVersion() {
    int version = -1;
    try {
        PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
        version = pInfo.versionCode;
    } catch (NameNotFoundException e1) {
        Log.e(this.getClass().getSimpleName(), "Name not found", e1);
    return version;

This will return the int chosen to identify your version in the market (VersionCode). Not the VersionName. To see how to change to code for this have a look at the code from Casebash.


PackageInfo‘s versionName is a public data member. You do not need to do anything special to get “the versionName for a running application from the PackageInfo Object type”. If you have a PackageInfo object named info, you access versionName via info.versionName.


Also there is a shortcut:

String version = new PackageInfo().versionName;

Leave a Reply

Your email address will not be published. Required fields are marked *