How to Retrieve Your Application’s Version Number in Android

It’s sad that I even need to post this but I find it increasingly difficult to search for answers to Android SDK questions. All I wanted to do was display the application version in the about screen. This one took me 3 pages of Google results to get to the answer. I swear I know how to search but for some reason googling the Android SDK flummoxes me.

It’s only two lines of code:

PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
String version = packageInfo.versionName;

You do have to catch a NameNotFoundException but that’s it. If you found this somewhere in the first 5 pages of Google search results then congratulations, you just saved 10 minutes of wading through useless and/or unrelated pages.