Вопрос

I have a class with one method that tries to retrieve meta-data from the manifest. Everything works fine except that the bundle that I create from the application info returns null values

Here's the code:

    private int getCurrentVersion(){
    int currVersion = 0;

    try {
        ApplicationInfo app = context.getPackageManager().getApplicationInfo(context.getPackageName(),PackageManager.GET_META_DATA);
        Bundle bundle = app.metaData;

        for (String key: bundle.keySet())
        {
          Log.d ("TEST", key + " is a key in the bundle");
        }

        Log.d("TEST","google: "+bundle.getString("com.google.android.gms.version"));
        Log.d("TEST","version: "+bundle.getString("dbVersion"));

        //currVersion = Integer.valueOf(bundle.getString("dbVersion"));
        currVersion = 1;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();         
    }

    return currVersion;
}


03-05 18:53:23.818: D/TEST(31400): com.google.android.gms.version is a key in the bundle
03-05 18:53:23.818: D/TEST(31400): dbVersion is a key in the bundle
03-05 18:53:23.828: D/TEST(31400): google: null
03-05 18:53:23.828: D/TEST(31400): version: null

As you can see I'm using some logs to see if the bundle is empty, but its not.

Это было полезно?

Решение

In some cases you need to use getInt() method:

bundle.getInt("com.google.android.gms.version"));

because the value of this meta-data is defined as an integer.

Log.d("TEST","google: "+bundle.getInt("com.google.android.gms.version"));

For example if the value defined in your meta-data is a String:

     <meta-data 
         android:name="com.elenasys.a"
         android:value="abcXJ434" />  

use:

   bundle.getString("com.elenasys.a"));   

if the value is an integer:

   <meta-data 
         android:name="com.elenasys.b"
         android:value="1234" />  

use getInt()

 bundle.getInt("com.elenasys.b"));

Другие советы

Also make sure the tag is under the manifest/application node in AndroidManifest.xml and not just under the root:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.readmetadata"
  android:versionCode="1"
  android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <meta-data android:name="dbVersion" android:value="1.0" />

        <activity android:name=".MainMenu" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="8" />
</manifest>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top