Home > front end >  how to create identifier on the fly
how to create identifier on the fly

Time:11-05

I my code, I have:

    public Bitmap loadIMG(Context context) {
        File pfile = getIMGPathFile(context);
        Bitmap bitmap = null;
        if (pfile.exists()) {
            try {
                //noinspection IOStreamConstructor
                bitmap = BitmapFactory.decodeStream(new FileInputStream(pfile));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            @SuppressLint("DefaultLocale") String from = String.format(FILE_PROD_PREFIX   Consts.FILE_NUMERIC_FORMAT, mId);
            bitmap = BitmapFactory.decodeResource(context.getResources(), context.getResources().getIdentifier(from, "drawable", context.getPackageName()));
        }
        return bitmap;
    }

But I get a warning:

Use of this function is discouraged because resource reflection makes it harder to perform build optimizations and compile-time verification of code. It is much more efficient to retrieve resources by identifier (e.g. R.foo.bar) than by name (e.g. getIdentifier("bar", "foo", null)).

How can I modify my code with a minimum of side effects please?

CodePudding user response:

What are you doing with this bitmap? Do you actually need the bitmap, or is the Drawable sufficient? If you' just need the drawable, the entire code is:

context.getDrawable(R.id.filename);

There is almost NEVER a good reason to use decodeResources. Resources are preloaded into memory for fast access- they're already decoded. So you can just use them as a drawable. Generally if you're trying to load one of several drawables like you seem to by creating a parameterized path, you should be using assets instead of resources.

CodePudding user response:

One solution would be to have an array of identifiers, and use mId (or some other expression) as an index in that array:

static final int ids[] = {R.drawable.img1,R.drawable.img2,....};
...
bitmap = BitmapFactory.decodeResource(context.getResources(),ids[mId]);
  • Related