Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;

public class Main {
    /**
     * Returns the string corresponding to a resource name in a specific package.
     *
     * @param context The parent context.
     * @param packageName The application's package name, e.g. "com.android.settings".
     * @param resName The short name of the resource, e.g. "ok".
     * @return A package-specific string, or {@code null}.
     */
    public static String getPackageString(Context context, String packageName, String resName) {
        final PackageManager pm = context.getPackageManager();

        final Resources packageRes;
        try {
            packageRes = pm.getResourcesForApplication(packageName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }

        final int resId = packageRes.getIdentifier(resName, "string", packageName);
        if (resId <= 0) {
            return null;
        }

        final String result;
        try {
            result = packageRes.getString(resId);
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
            return null;
        }

        return result;
    }
}