When I wrote code several times, I encountered the use of getresource (). At that time, I wrote it in a common class to load images in assets, but the code reported an error. Later I found that this method requires context, but I was eager to write and did not understand it carefully. As a result, I had no idea how to modify and pass the context, finally, in order to avoid this problem, we put it into the class that inherits the activity.
Now we have encountered this problem, and we have to solve it now.
In fact, you only need to call the connection context parameter in the method or in the constructor:
The Code is as follows:
/*** Load image resources from assets * use this method to load image resources when using baseadapter in the gridview in the final optimization code **/package COM. example. changeyouvice. util; import Java. io. ioexception; import Java. io. inputstream; import COM. example. changeyourvice. voicechangeactivity; import android. content. context; import android. content. res. assetmanager; import android. graphics. bitmap; import android. graphics. bitmapfactory; import android. util. log; public class G Ridviewresource {private context; private final static int max_resource_length = 18; Public bitmap [] mbitmaparray = NULL; Public gridviewresource (context) {This. context = context;} // load image resources to the bitmap array public bitmap [] fillbitmaparray () {string name = "gridtn"; mbitmaparray = new bitmap [max_resource_length]; for (INT I = 0; I <max_resource_length; I ++) {int namenum = I; string fil Ename = Name + String. valueof (namenum); log. E ("FILENAME", filename); mbitmaparray [I] = loadfromasset (context, filename);} return mbitmaparray;} // load image resources from assets private bitmap loadfromasset (context, string filename) {bitmap mbitmap = NULL; log. E ("loadfromasset", "execute"); assetmanager AM = context. getresources (). getassets (); log. E ("loadfromasset", "Execute ?? "); Try {inputstream is = aM. open (filename); mbitmap = bitmapfactory. decodestream (is); is. close ();} catch (ioexception e) {e. printstacktrace ();} return mbitmap ;}}
Code called in activity:
protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ~~~~~~~~~~~~~~~~~ mGridViewResource = new GridViewResource(this); mBitmap = mGridViewResource.fillBitmapArray();~~~~~}
Solve the problem when getresource () is used in classes other than the inherited activity class