1. Download our Official Android App: Forums for Android!

Apps How to retrive all elements from Res/Raw folder in one shot at run time

Discussion in 'Android Development' started by murali.lancer, Jan 11, 2010.

  1. murali.lancer

    murali.lancer Newbie
    Thread Starter
    Rank:
    None
    Points:
    16
    Posts:
    18
    Joined:
    Sep 17, 2009

    Sep 17, 2009
    18
    1
    16
    hi all,
    I have some zip files in res/raw folder ,normally i can get them by using

    like getResources().openRawResources(R.raw.file name );
    by mentioning file name at compile time(static loading) .so that i can un zip them .and now i have so many zip files there in raw folder ,so programatically i need to change the filename according to the requirement .
    so if anybody knows this pls give me idea.

    thanks and Regards
    Murali dhuli
    Android developer.
     

    Advertisement

  2. markb

    markb Well-Known Member
    Rank:
    None
    Points:
    63
    Posts:
    148
    Joined:
    Sep 14, 2009

    Sep 14, 2009
    148
    26
    63
    Software Developer (Java, C, Web, Unix)
    Birmingham, UK
    Hi Murali,

    I can think of one way of doing this. I'm not saying it's the best, but it works.

    The following code uses Java reflection to get the members of the R.raw class, retrieves their values, and returns the resource IDs in an array.

    Code (Text):
    1.  
    2.     private int[] getAllRawResources() {
    3.       int[] ids = null ;
    4.       R.raw r = new R.raw() ;
    5.        
    6.       Field fields[] = R.raw.class.getDeclaredFields() ;
    7.       ids = new int[fields.length] ;
    8.        
    9.       try {
    10.     for( int i=0; i<fields.length; i++ ) {
    11.       Field f = fields[i] ;
    12.       ids[i] = f.getInt(r) ;
    13.       Log.i(TAG, "R.raw."+f.getName()+" = 0x"+Integer.toHexString(ids[i])) ;
    14.         }
    15.       } catch (IllegalArgumentException e) {
    16.         // TODO Auto-generated catch block
    17.     e.printStackTrace();
    18.       } catch (IllegalAccessException e) {
    19.         // TODO Auto-generated catch block
    20.         e.printStackTrace();
    21.       }
    22.  
    23.       return ids ;
    24.     }
    25.  
    My R class looks like this:

    Code (Text):
    1.  
    2. public final class R {
    3. . . .
    4.     public static final class raw {
    5.         public static final int levels=0x7f040000;
    6.         public static final int tunnels=0x7f040001;
    7.     }
    8.    . . .
    9. }
    10.  
    And the code generates the following output in the log:

    Code (Text):
    1.  
    2. 01-11 21:39:41.719: INFO/TempestActivity(759): R.raw.levels = 0x7f040000
    3. 01-11 21:39:55.027: INFO/TempestActivity(759): R.raw.tunnels = 0x7f040001
    4.  
    I hope that helps.
    If anyone has a better way, I'd be curious to hear about it. :)

    Regards,

    Mark
     

Share This Page

Loading...