DEV
DEV

Reputation: 41

Android getString method

i'm trying to concatenate a String value setted into string.xml with a date using this code:

holder.time.setText(date.getHours()+" " + getString(R.string.ore));

but i recive error: can not resolve method. I have try to this code:

holder.time.setText(date.getHours()+" " +R.string.ore);

works but the value R.string.ore is retrieved as int value and not string, but i need a string value I need to use the value by string.xml and not using a simple string example "ore"

Any help?

Upvotes: 0

Views: 2388

Answers (3)

Birat Bade Shrestha
Birat Bade Shrestha

Reputation: 870

Try this,

Calendar calendar = Calendar.getInstance();
holder.time.setText(calendar.get(Calendar.HOUR)+" " +getString(R.string.ore));

This may help you.

Upvotes: 0

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17132

If you're in an activity's context, use this:

getResources().getString(R.string.ore);

If you're in a fragment's context, use this:

getActivity().getResources().getString(R.string.ore);

If you're within an adapter, you need to pass the container activity's context to it via the adapter's constructor.

// When creating the adapter, pass the activity's context
// keeping in mind the notes above
YourAdapter adapter = new YourAdapter(this, ...);

And from within the adapter:

private Context mContext; // A member variable of the adapter class

public YourAdapter(Context context, ...) {
    mContext = context;
}

Then you can get your string resource this way:

mContext.getResources().getString(R.string.ore);

Upvotes: 3

Blackbelt
Blackbelt

Reputation: 157437

getString is a method of Context. If can't resolve it, it means that your class is not a subclass of Context. You could use

holder.time.getContext()

to retrieve the Context you used to inflate that TextView and access getString(). Eg holder.time.getContext().getString(R.string.hour)

Upvotes: 2

Related Questions