Skip to content Skip to sidebar Skip to footer

Android How To Use String Resource In A Java Class

In my java class I want to use a string resource from strings.xml. for that I have to use like below, getString(R.string.address) if my class is an activity then its taking. But m

Solution 1:

A class does not have a context and to use a string resource a context is needed. So just call the class from an activity and give a parameter context and within your class constructor just use that context to get the string resource.

In your custom class you need to import the R namespace for the project to get the resource Id.

import com.myrandomapp.R;

Then to get the actual string

context.getString(R.string.COOL_STRING)

Solution 2:

You can pass the context of the Activity class to the java class and access the resources.

From your Activity Class

Helperhelper=newHelper(this);

Your Java class

publicclassHelper {

    Helper(Context c){
        c.getString(R.string.address);
    }
}

Solution 3:

You can create a static Application Context in your custom Application class

publicclassAppextendsApplication{

    privatestaticContext mContext;

    @OverridepublicvoidonCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    publicstaticContextgetContext(){
        return mContext;
    }
}

Then you just need to call App.getContext().getResources() to get any resource values.

Just remember that this Context is Application type, so there are things that this Context is not good to use. Read this for further info.

Solution 4:

You could done if you add this line:

// this is the object itself, and idString is the ID String bound to the literal.this.getString(R.string.idString)

I hope this comment helps you!

Brs.

Post a Comment for "Android How To Use String Resource In A Java Class"