User versionName value of AndroidManifest.xml in code

AndroidAndroid Manifest

Android Problem Overview


The AndroidManifest.xml contains the version name of the application, something like

android:versionName="1.0"

Now the question - is it somehow possible to access this version name in the source code, so that I can display it for example in an About Dialog?

Android Solutions


Solution 1 - Android

If you use ADT and Eclipse:

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

If you use Gradle, there is an easier way, since it puts the data into BuildConfig for you:

String version = BuildConfig.VERSION_NAME;

Solution 2 - Android

Konstantin's answer (above) is correct, but for what it's worth I found that I got a compiler error if I did not catch a NameNotFoundException , as follows:

import android.content.pm.PackageManager.NameNotFoundException;
try {
    String version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
    Log.e("tag", e.getMessage());
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDonGruView Question on Stackoverflow
Solution 1 - AndroidKonstantin BurovView Answer on Stackoverflow
Solution 2 - AndroidDMHView Answer on Stackoverflow