Adding and Using Meta-data in Android Manifest for Some Common Values

by Sasikumar 2014-04-08 17:55:47

Meta-data in Android Manifest file for Some Common/Global values :
Step 1: In XML file add the meta data tag as given in following example. Name in the meta tag is used to retrieve the value from it.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hiox.metadatademo"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.hiox.metadatademo.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<meta-data android:name="baseUrl" android:value="http://www.hiox.org" />
<meta-data android:name="passKey" android:value="PASSKEY_VALUE" />
</application>

</manifest>


Step 2: To get back the value from the meta tag in your activity use the following code,
try {
ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
Bundle myBundle = appInfo.metaData;
String passKey = myBundle.getString("passKey");
String baseUrl = myBundle.getString("baseUrl");
System.out.println("Pass key : " + passKey);
System.out.println("Base URL : " + baseUrl);
} catch (NameNotFoundException e) {
Log.e("Meta Data Demo","Meta Data Name Not Found: " + e.getMessage());
} catch (NullPointerException e) {
Log.e("Meta Data Demo", "Meta Data Null Pointer Exception: " + e.getMessage());
} catch (Exception e) {
Log.e("Meta Data Demo", "Some Other Exception: " + e.getMessage());
}

Data can be retrieved in the above method using the application info and bundle methods.

Note : Meta data can store any data of the datatype boolean, float, int, or String and retrieved using getString for String, getint() for int and so on...
1173
like
0
dislike
0
mail
flag

You must LOGIN to add comments