Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android how to use string resource in a java class

Tags:

string

android

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 my class is a simple java class , how can I use there?

Is it possible? Thank you

like image 410
Narendra Avatar asked Nov 12 '11 05:11

Narendra


People also ask

How do you use string resources in Java?

android:text="@string/hello" /> String string = getString (R. string. hello); You can use either getString(int) or getText(int) to retrieve a string.

What is string resource in Android?

A string resource provides text strings for your application with optional text styling and formatting. There are three types of resources that can provide your application with strings: String. XML resource that provides a single string. String Array.

What is extract string resource in Android?

In Android Studio while adding TextView to the layout xml file, it is very convenient to use "Extract String Resource" to add string name to strings.


1 Answers

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) 
like image 86
Jyosna Avatar answered Oct 08 '22 23:10

Jyosna