How to read many file from raw resource in loop?

2019-02-15 18:49发布

i have many text file and want to put it in for loop ! i get an Extra that have Resource name from last activity (s) and have an array that have Resource name of my text file from raw Resource is start from {d0,d1,d2,d3, ...,d79} and i want to check name(s) and array name and put the find name to resource!!! i have error on (res=R.raw.(d[i])) my code :

    int res = 0;
    for (int i = 0; i <=79; i = i + 1) {
        if (s.equals(d[i])){
            res=R.raw.(d[i])
        }
    } 
    inputstream = getResources().openRawResource(res);

2条回答
我命由我不由天
2楼-- · 2019-02-15 19:27

You can use getIdentifier (String name, String defType, String defPackage) for fetching resource id dynamically,

ArrayList<Integer> id = new ArrayList<Integer>();
for (int i = 0; i <= 79; i++) {
  id.add(getResources().getIdentifier("d"+i, "raw", getPackageName()));
}

Now you will have all the resources id's inside id ArrayList

查看更多
混吃等死
3楼-- · 2019-02-15 19:36

I have 6 variations of resources in one place I need to read.

    try
     {
        for (int i = 0; i < 6; i++ )
         {
              String fname = "p" + i;
              int id = context.getResources().getIdentifier(fname, "drawable", "com.example.yourproject");
              if (id == 0)
              {
                  Log.e(TAG, "Lookup id for resource '"+fname+"' failed");
                  // graceful error handling code here
              }
             scoresBm[i] =  (Bitmap) BitmapFactory.decodeResource(context.getResources(), id);
         }
    }
    catch(Exception E)
    {
    }
查看更多
登录 后发表回答