androidandroidxedittextpreference

How to get the app version in EditTexPreference android


I would like to get the App Version in EditTextPreference for my app.

App Name:

--App Name --

Version

1.0

for example:

enter image description here

it should reflect the version name in build.gradle(app)


Solution

  • You can try the following code to get the app version name:

    PackageManager pm = getApplicationContext().getPackageManager();
    String pkgName = getApplicationContext().getPackageName();
    PackageInfo pkgInfo = null;
    try {
       pkgInfo = pm.getPackageInfo(pkgName, 0);
    } 
    catch (PackageManager.NameNotFoundException e) {
       e.printStackTrace();
    }
    String versionName = pkgInfo.versionName;
    

    The versionName variable stores the version name.

    For fragments:

    PackageInfo pkgInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
    version = pkgInfo.versionName;