In the process of Android development, the Getresources () method is referenced in a non-activity class (Where the class name is assumed to be Mynewclass), as follows:
Bitmap bmp = Bitmapfactory.decoderesource (Getresources (), r.drawable.marker_red);
Result error Message Tip: There is no getresources () method in Mynewclass.class.
In Baidu and Google on a variety of search, there is no suitable solution.
Someone who solves this:
You can pass pointers to your activity, where you call the Getapplicationcontext () method, or you want to use getcontext () .
One, instead of bitmap bmp = Bitmapfactory.decoderesource (Context.getresources (), r.drawable.marker_red); and bitmap bmp = Bitmapfactory.decoderesource (This.getresources (), r.drawable.marker_red);
If you try, you know it's not possible (I can't do it anyway, but if it should be OK in the Activity Class).
Second, make the following changes in Acitivity:
public static Resources resourcesinstance;
Resourcesinstance=this.getresources ();
Mynewclass.class So quote:
Bitmap Bitmap = Bitmapfactory.decoderesource (myactivity.resourcesinstance, r.drawable.test);
In this way, the code is not wrong, but there is a nullpointerexception program run crashes.
Although the problem is not resolved, but to see such two words:
"To pass a Context (such as activity or application,service) in the constructor of a class to come in" and "Android.content.Context, Getresources based on activity. "
Inspired by this, two solutions are found:
Method One: Create the getresources () method in Mynewclass.class:
Private Resources getresources () {
TODO auto-generated Method Stub
Resources mresources = null;
Mresources = Getresources ();
return mresources;
}
You will find that the error is gone and the result is normal.
Method Two: The context is passed in the Myactivity.class constructor function. Declares a context, and constructs the method GetContext (). The specific code is as follows:
To perform context transfer in Myactivity.class:
public class MyActivity extends Activity {
......
......
private static context context = NULL;
......
......
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.view);
......
......
Public static Context GetContext () {
return Context;
}
To make a reference to a method in Mynewclass.class:
Bitmap bmp = Bitmapfactory.decoderesource (Myactivity.getcontext (). Getresources (), r.drawable.marker_red);
--------------------------------------------------------------------------------------------------------------- -----------------------------------------------------------
This is the workaround for the non-activity class reference Getresources () method problem that was created for yourself.
Android non-Activity class reference Getresources () method Problem Solving method