Get string from extra or from metadata. - Android App

Android examples for App:Manifest

Description

Get string from extra or from metadata.

Demo Code


import java.util.Locale;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

public class Main{
    private static final String TAG = "AboutUtils";
    /**/*w w  w  . j  a va 2 s  .  c  o m*/
     * Get string from extra or from metadata.
     * 
     * @param context
     * @param packagename
     * @param intent
     * @param extra
     * @param metadata
     * @return
     */
    public static String getStringExtraOrMetadata(
            final MetaDataReader metaDataReader, final Context context,
            final String packagename, final Intent intent,
            final String extra, final String metadata) {
        if (intent.hasExtra(extra) && intent.getStringExtra(extra) != null) {
            return intent.getStringExtra(extra);
        } else {
            //Try meta data of package
            Bundle md = metaDataReader.getBundle();

            if (md != null && !TextUtils.isEmpty(md.getString(metadata))) {
                return md.getString(metadata);
            } else if (md != null) {
                //Still try metadata but don't expect a ready string (get it from the resources).
                try {
                    int id = md.getInt(metadata);
                    Resources resources = context.getPackageManager()
                            .getResourcesForApplication(packagename);
                    String text = resources.getString(id);
                    if (!TextUtils.isEmpty(text)) {
                        return text;
                    }
                } catch (NameNotFoundException e) {
                    Log.e(TAG, "Package name not found ", e);
                } catch (NumberFormatException e) {
                    Log.e(TAG, "Metadata not valid id.", e);
                } catch (Resources.NotFoundException e) {
                    Log.e(TAG, "Resource not found.", e);
                }
            }
            return "";
        }
    }
}

Related Tutorials