How can you get the Manifest Version number from the App's (Layout) XML variables?

124,694

Solution 1

There is not a way to directly get the version out, but there are two work-arounds that could be done.

  1. The version could be stored in a resource string, and placed into the manifest by:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
         package="com.somepackage"
         android:versionName="@string/version" android:versionCode="20">
    
  2. One could create a custom view, and place it into the XML. The view would use this to assign the name:

    context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    

Either of these solutions would allow for placing the version name in XML. Unfortunately there isn't a nice simple solution, like android.R.string.version or something like that.

Solution 2

I believe that was already answered here.

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

OR

int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;

Solution 3

You can use the versionName in XML resources, such as activity layouts. First create a string resource in the app/build.gradle with the following snippet in the android node:

applicationVariants.all { variant ->
    variant.resValue "string", "versionName", variant.versionName
}

So the whole build.gradle file contents may look like this:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '24.0.0 rc3'
    defaultConfig {
        applicationId 'com.example.myapplication'
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 17
        versionName '0.2.3'
        jackOptions {
            enabled true
        }
    }
    applicationVariants.all { variant ->
        variant.resValue "string", "versionName", variant.versionName
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
} 

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.android.support:support-v4:23.3.0'
}

Then you can use @string/versionName in the XML. Android Studio will mark it red, but the app will compile without issues. For example, this may be used like this in app/src/main/res/xml/preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
        android:title="About"
        android:key="pref_key_about">

        <Preference
            android:key="pref_about_build"
            android:title="Build version"
            android:summary="@string/versionName" />

    </PreferenceCategory>


</PreferenceScreen>

Solution 4

IF you are using Gradle you can use the build.gradle file to programmatically add value to the xml resources at compile time.

Example Code extracted from: https://medium.com/@manas/manage-your-android-app-s-versioncode-versionname-with-gradle-7f9c5dcf09bf

buildTypes {
    debug {
        versionNameSuffix ".debug"
        resValue "string", "app_version", "${defaultConfig.versionName}${versionNameSuffix}"
    }
    release {
        resValue "string", "app_version", "${defaultConfig.versionName}"
    }
}

now use @string/app_version as needed in XML

It will add .debug to the version name as describe in the linked article when in debug mode.

Solution 5

I solved this issue by extending the Preference class.

package com.example.android;

import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;

public class VersionPreference extends Preference {
    public VersionPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        String versionName;
        final PackageManager packageManager = context.getPackageManager();
        if (packageManager != null) {
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                versionName = packageInfo.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                versionName = null;
            }
            setSummary(versionName);
        }
    }
}

Then in my preferences XML:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <com.example.android.VersionPreference android:title="Version" />
</PreferenceScreen>
Share:
124,694

Related videos on Youtube

PearsonArtPhoto
Author by

PearsonArtPhoto

I'm an systems engineer, with some focus on complex systems, signal processing and a bit of control systems. My current job title is "Senior Systems Engineer". I am also a hobby photographer, and avid Android and Unity programmer. I am the programmer of the Android app Psychic Tester, Ham Finder, Qsl Mapper, and the game Rocket Bowl. I am also the author of the blog, The Making of a Ham, and the photographer on PearsonArtPhoto.com. I gained the most fame from creating http://www.whereisroadster.com/, and run a YouTube Channel http://www.youtube.com/c/whereisroadster/ To see some of my photography, check out the following sites: Portrait Portfolio Landscape Portfolio (Hosted by Smugmug) (25% off using code Stack) Shutterstock Bigstockphoto Fotolia Dreamstime

Updated on June 24, 2020

Comments

  • PearsonArtPhoto
    PearsonArtPhoto almost 4 years

    I would like to have a way to reference the project's manifest version number in the main part of the code. What I have been doing up until now is to link the version number in a String XML file to the manifest (@string/Version). What I would like to do is to do it the other way around, link a string XML variable to the version in the manifest. The reason? I'd like to only have to change the version number in one location, the manifest file. Is there any way to do this? Thanks!

    • PearsonArtPhoto
      PearsonArtPhoto over 11 years
      This is NOT a duplicate. The question in question asks how to do the same thing in CODE, I'm asking in XML. Two very different constructs in Android programming...
  • PearsonArtPhoto
    PearsonArtPhoto over 13 years
    Almost, but not quite... What I'd like to do is to reference it to an XML code, but it looks like that might not be possible, so...
  • PearsonArtPhoto
    PearsonArtPhoto over 13 years
    I was afraid of that... Thanks for the help!
  • Aaron Klap
    Aaron Klap almost 12 years
    Thank you so much!!! I have been looking everywhere for this: String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
  • Gerrit-K
    Gerrit-K almost 11 years
    a little note to 1.: it's working but I think it's discouraged since I get a warning telling me The android:versionName cannot be a resource url, it must be a literal string
  • Konstantin Burov
    Konstantin Burov almost 11 years
    @Shubh I don't think so.
  • numediaweb
    numediaweb over 10 years
    What I did is leave the manifest version name untouched (but update it whenever a new release) and use the string.xml to store the value that I'll be using across the app.
  • Suge
    Suge over 10 years
    I use like this:<Preference android:title="Version" android:summary="?android:attr/versionName" ></Preference>, but show as ?16843292.What's wrong?
  • seastland
    seastland over 10 years
    Oops. I must have been thinking Preference XML based on another comment.
  • Mafro34
    Mafro34 over 10 years
    I'm not sure but think this is for later API's?
  • Mafro34
    Mafro34 over 10 years
    @PearsonArtPhoto actually, where does it say that?
  • Mathijs Segers
    Mathijs Segers almost 9 years
    Nevertheless, I will just copy and paste his answer anyway.
  • Adrian C.
    Adrian C. about 8 years
    For AndroidStudio, the manifest versionName is override by the one set in build.gradle file
  • Makotosan
    Makotosan about 8 years
    BuildConfig.VERSION_NAME is already a string, no need to call toString() on it.
  • Mullazman
    Mullazman about 8 years
    Habit. Fair enough
  • Arun Shankar
    Arun Shankar about 8 years
    we can use it. please check my answer. I am using it in my app
  • DenisGL
    DenisGL almost 8 years
    Could you explain the "magic" (or my Gradle ignorance ;-) behind these lines?
  • Arun Shankar
    Arun Shankar almost 8 years
  • Neurotransmitter
    Neurotransmitter almost 8 years
    This is better, than programmatic style.
  • Samik Bandyopadhyay
    Samik Bandyopadhyay over 7 years
    Wonderful solution. Thanks a ton.
  • MikeL
    MikeL over 7 years
    There are cases when calling this in your project may get different result from what you would expect. For example if you use an android submodule in your project and you call it from the code of the submodule it will reference to build config of the submodule which may have different version. Or if you call it from the code of your project you may reference by mistake to build config of your submodule and get the same result. Just be careful and double check that you reference to a proper package of the build config.
  • DenisGL
    DenisGL over 7 years
    When I use this string in a layout, I get a warning from Android Studio: "Couldn't resolve resource @string/version_name". Any idea how to get rid of it?
  • Arun Shankar
    Arun Shankar over 7 years
    @DenisGL have you add variant.resValue "string", "versionName", variant.versionName in build.gradle ?
  • jobbert
    jobbert over 7 years
    Add BuildConfig.VERSION_NAME to your answer for gradle fokes.
  • k2col
    k2col over 7 years
    this seemed like a great answer when I read it but sadly it doesn't work, at least not in the latest Android Studio.
  • Arun Shankar
    Arun Shankar over 7 years
    I am using the latest and still works for me. I use this and several other variables like this. @k2col what error do u get while compiling? Pls post ur gradle code
  • pepan
    pepan about 7 years
    This should be considered the best answer.
  • pepan
    pepan about 7 years
    doesn't work; returns funny number which @Suge pointed out above
  • A_rmas
    A_rmas about 7 years
    doesnot work at all and returns random value as previously posted
  • A_rmas
    A_rmas about 7 years
    It worked but showing red mark|| error in xml though it runs
  • Arun Shankar
    Arun Shankar about 7 years
    @A_rmas what is the error showing when you hover on the red highlight?
  • A_rmas
    A_rmas about 7 years
    @ArunElectra it is cannot resolve symbol. but it allows run and generate apk. it is just the marking of error.
  • Patrick
    Patrick over 6 years
    Didn't work for me. Tried to use it in my TextView but it says "No resource found that matches the given name (at 'text' with value '@string/versionName')."
  • CrandellWS
    CrandellWS over 5 years
    as noted and linked It is a Constant Value of 16843292 (0x0101021c) hence why @suge got that specific value
  • CrandellWS
    CrandellWS over 5 years
    Try using this guide: medium.com/@manas/…
  • Koorosh Ghorbani
    Koorosh Ghorbani over 5 years
    this is the best solution , with this solution we can show different versions for different variants
  • Raheel Hasan
    Raheel Hasan over 5 years
    best answer ever!!
  • Andris
    Andris over 4 years
    Wow, great solution!!! Only bad thing is that AndroidStudio thinks that string is not recognised, but apk generates as it should!
  • Ishaan Kumar
    Ishaan Kumar about 4 years
    difference is BuilConfig is provided by Gradle whereas getting it at runtime is by PackageManager (OS)