get String resource - Android App

Android examples for App:Resource

Description

get String resource

Demo Code


//package com.java2s;
import android.content.Context;

public class Main {
    public static String getString(Context ctx, String name) {
        int id = getStringResource(ctx, name);
        String str = "";
        if (id > 0) {
            str = ctx.getResources().getString(id);
        }//from  w  w w.  j a v a  2s.  c  o  m
        return str;
    }

    public static int getStringResource(Context ctx, String name) {
        String packageName = ctx.getPackageName();
        try {
            Object obj;
            obj = Class.forName(packageName + ".R$string").newInstance();
            return Class.forName(packageName + ".R$string")
                    .getDeclaredField(name).getInt(obj);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}

Related Tutorials