Using Getresources() in Non-Activity Class

Using getResources() in non-activity class

You will have to pass a context object to it. Either this if you have a reference to the class in an activty, or getApplicationContext()

public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
RegularClass regularClass = new RegularClass(this);
}
}

Then you can use it in the constructor (or set it to an instance variable):

public class RegularClass(){
private Context context;

public RegularClass(Context current){
this.context = current;
}

public findResource(){
context.getResources().getXml(R.xml.samplexml);
}
}

Where the constructor accepts Context as a parameter

How to call getResources() from a class which has no context?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.

This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources.
You can pass context in the constructor like

public classname(Context context, String s1) 
{
...
}

android getResources() from non-Activity class

I have found in Android it is very important with Activities (and most other classes) not to have references to them in static variables. I try to avoid them at all costs, they love causing memory leaks. But there is one exception, a reference to the application object, which is of course a Context. Holding a reference in a static to this will never leak memory.

So what I do if I really need to have a global context for resources is to extend the Application object and add a static get function for the context.

In the manifest do....
<application android:name="MyApplicationClass" ...your other bits....>

And in Java....

public class MyApplicationClass extends Application
{
private Context appContext;

@Override
public void onCreate()
{//Always called before anything else in the app
//so in the rest of your code safe to call MyApplicationClass.getContext();
super.onCreate();
appContext = this;
}

public static Context getContext()
{
return appContext;
}
}

Getting resources from non-activity classes

So it's not pretty but I found a solution.
In onCreate for the Main activity (The only place this info is even getting used right now), I've put the following code:

CreepIDs.context = getApplicationContext();

Since context is static public anyways, I'm directly assigning a value to it when the app starts. I only need the context so I can call resources and it won't be used for anything else so I don't think this will be a problem for me at all.

In the end, using the special App class just didn't work for me.

Thanks for everyone's assistance.

Android. Get string resource for a non-activity class

You have to use reference to a Context to access resources.
I'd recommend extending the Application class and creating an Application Singleton, then calling:

MyApplication.getInstance().getString(R.string.myString);

Or injecting it into your class of choice.

Problem with this approach is that it would make your class harder to test, since now it uses the Android context. I'd recommend passing a string as a dependency into the non-activity class of choice via the constructor or preferred method.

public MyClass(String string){
}

How to get String in a non activity class?

The issue which you are getting is NullPointerException on _context.

I think it is because you have declared _context as static variable and convertTimeToHoursMinutesString as static method.

But you are initializing the _context in constructor.

public CommonUtils(Context context) {
this._context = context;
}

But as the method is static so you would not be creating an object to call it. Instead you would be calling it directly by class name, like CommonUtils.convertTimeToHoursMinutesString. So the constructor never gets called, hence _context is null.

If you want to keep it static then you can do it like this,

public static String convertTimeToHoursMinutesString(Context _context, long lTimeinMillis){
// Calculate hours first.
long hours = TimeUnit.MILLISECONDS.toHours(lTimeinMillis);
lTimeinMillis -= TimeUnit.HOURS.toMillis(hours);
// Calculate minutes then.
long minutes = TimeUnit.MILLISECONDS.toMinutes(lTimeinMillis);
lTimeinMillis -= TimeUnit.MINUTES.toMillis(minutes);
// Calculate seconds last.
//long seconds = TimeUnit.MILLISECONDS.toSeconds(lTimeinMillis);

StringBuilder str = new StringBuilder(64);
str.append(hours);

str.append(_context.getString(R.string.Hour));
str.append(minutes);
str.append(_context.getString(R.string.Min));
//str.append(seconds);
//str.append(" Seconds");
return(str.toString());
}

Also you can access getString() like context.getResources().getString(R.string.YOUR_STRING);

getResources in non-activity class

Have you tried just getting the bitmap in the Activity and then passing that to the constructor of your GameScreen?



Related Topics



Leave a reply



Submit