Android xml/assets/raw resource usage details

Source: Internet
Author: User

Android xml/assets/raw resource usage details
I. Introduction to assets/xml/raw resources 1. assets Resource Directory: Resources stored in the assets Directory represent native resources that cannot be directly accessed by the application. These files are stored on the device and will not be compiled in binary format, the access method is through the file name rather than the resource ID. The application uses AssetManager to read resource files in byte streams. The difference between assets and res/raw is that assets supports sub-directories in any depth. These resource files do not generate any resource IDs. The steps for an Android app to access resources in the assets folder are as follows: (1) Call getAssets () in the Activity to obtain the AssetManager reference; (2) use AssetManger's open (String fileName, int accessMode) method To Get The InputStream of the input file. Note that fileName cannot be a directory. (3) read data from the input stream InputStream, and close the input stream (close () after reading the data. (4) Call AssetManager. close () to close the AssetManager sample code:

  1. AssetManager assetManager = getResources (). getAssets (); // gets AssetManager reference for managing assets directory resources
  2. InputStream inputStream = assetManager. open ("data.txt"); // gets the input stream of the assets/data.txt resource file.
  3. InputStreamReader inputReader =NewInputStreamReader (inputStream );
  4. BufferedReader bufReader =NewBufferedReader (inputReader );
  5. While(Line = bufReader. readLine ())! =Null) // Read the input stream data by row
  6. Result + = line;
  7. ReturnResult;
  8. Or
  9. InputStream inputStream = getResources (). getAssets (). open ("data.txt"); // obtain the input stream of the assets/data.txt File
  10. IntLength = inputStream. available (); // get the number of bytes of the object
  11. Byte[] Buffer =New Byte[Length]; // create a length byte array
  12. InputStream. read (buffer); // read the data in the file to the byte array.
  13. String result = EncodingUtils. getString (buffer, "UTF-8"); // obtain String data2. res/raw Resource Directory: Resources stored in the raw directory represent native resources that cannot be directly accessed by the application. These files will not be compiled into binary format and will not be stored on the device, the application accesses Resources in the raw directory through the resource ID (R list index. The application uses openRawResource to read resource files in the form of byte streams. raw does not support multi-level sub-directories. Sample Code:
    1. InputStreamReader inputReader = new InputStreamReader (getResources (). openRawResource ("data.txt "));
    2. BufferedReader bufReader = new BufferedReader (inputReader );
    3. While (line = bufReader. readLine ())! = Null) // read input stream data by row
    4. Result + = line;
    5. Return result;
      3. res/xml Resource Directory: This directory is used to store common XML files. Like/res/drawable resources, xml resources will be compiled into binary format and stored in the final installation package. The xml directory does not support multi-level sub-directories. In development, you can use the R class to access these file resources and parse the content. The XML resource content is as follows res/xml/persons. xml: Zhang San Li Si
      Wang Wu
      Zhao Liu

      Sample Code:
      1. XmlResourceParser xmlParser = getResource (). getXml (R. xml. persons );
      2. // Obtain the XmlResourceParser parser reference for res/xml/data. xml
      3. StringBuilder sb =NewStringBuilder ("");
      4. While(XmlParser. getEventType ()! = XmlPullParser. END_DOCUMENT) {// determine whether to read the XML document.
      5. If(XmlParser. getEventType () = XmlPullParser. START_TAG) {// The start tag is displayed.
      6. String tagName = xmlParser. getName (); // obtain the Tag Name
      7. If(TagName. equals ("person") {// obtain the corresponding Attribute Based on the Tag Name
      8. String personAge = xmlParser. getAttributeValue (Null, "Age"); // obtain the attribute value based on the attribute name
      9. String personSex = xmlParser. getAttributeValue (1); // obtain the attribute value based on the attribute name
      10. String person = xmlParser. nextText (); // obtain the value of the text node.
      11. String onePerson = "name:" + person + "Gender:" + personSex + "age:" + personAge;
      12. Sb. append (onePerson );
      13. }
      14. Sb. append ("\ n ");
      15. }
      16. XmlParser. next (); // gets the next event of the parser
      17. }
      18. System. out. println (sb. toString ());
      19. }
        The result is as follows:
        Summary: The PULL parser is an open-source project. The Android platform has a built-in PULL parser, And the Android system uses the PULL parser to parse Various XML documents. When PULL parses an XML file, it calls back the value defined in XmlResourceParser to indicate the beginning and end of the document and the end of the node (The Event Callback type), which is as follows:. read to the beginning of the XML document (Declaration) and return: XmlPullParser. START_DOCUMENT B. after reading the XML document, return XmlPullParser. END_DOCUMENT c. read to the XML node and return XmlPullParser. START_TAG d. when the XML node is read, XmlPullParser is returned. END_TAG e. returned XML text: XmlPullParser. there are several main methods for TEXT XmlPullParser:. xmlPullParser. getEventType (): Get the callback type of the current event B. xmlPullParser. getName (): get the name of the current node c. xmlPullParser. getAttributeValue (int index): Get the node attribute value d based on the id. xmlPullParser. getAttributeValue (String namespace, String name): obtains the node attribute value e Based on the name. xmlPullParser. netxText (): When the callback node START_TAG is used, the node content is obtained through this method.Ii. Source Code practice 1. Effect demonstration

        (2) source code MainActivity. java
        1. Package com. example. assetsresource;
        2.  
        3. Import java. io. IOException;
        4. Import java. io. InputStream;
        5. Import java. io. Reader;
        6.  
        7. Import org. apache. http. util. EncodingUtils;
        8. Import org. xmlpull. v1.XmlPullParser;
        9. Import org. xmlpull. v1.XmlPullParserException;
        10.  
        11. Import android. app. Activity;
        12. Import android. content. res. AssetManager;
        13. Import android. content. res. XmlResourceParser;
        14. Import android. OS. Bundle;
        15. Import android. view. View;
        16. Import android. view. View. OnClickListener;
        17. Import android. widget. Button;
        18. Import android. widget. TextView;
        19.  
        20. /**
        21. * Project name/version: assetsResource/v1.0
        22. * Package name: com. example. assetsresource
        23. * Class description: parses files in the assets, xml, and raw directories.
        24. * Created by: jiangdongguo: 11:12:47
        25. * Blog: http://blog.csdn.net/u012637501
        26. */
        27. Public class MainActivity extends Activity {
        28. Private Button xmlBtn = null;
        29. Private Button rawBtn = null;
        30. Private Button assetsBtn = null;
        31. Private TextView context = null;
        32.  
        33. Private void init (){
        34. XmlBtn = (Button) findViewById (R. id. parserXML );
        35. RawBtn = (Button) findViewById (R. id. parserRaw );
        36. AssetsBtn = (Button) findViewById (R. id. parserAssets );
        37. MyClickListener listener = new myClickListener ();
        38. XmlBtn. setOnClickListener (listener );
        39. RawBtn. setOnClickListener (listener );
        40. AssetsBtn. setOnClickListener (listener );
        41. Context = (TextView) findViewById (R. id. text );
        42. }
        43.  
        44. @ Override
        45. Protected void onCreate (Bundle savedInstanceState ){
        46. Super. onCreate (savedInstanceState );
        47. SetContentView (R. layout. main );
        48. Init ();
        49. }
        50.  
        51. /**
        52. * Internal class description: internal class implementation event monitor blog address: http://blog.csdn.net/u012637501
        53. */
        54. Class myClickListener implements OnClickListener {
        55. Public void onClick (View v ){
        56. Switch (v. getId ()){
        57. Case R. id. parserAssets:
        58. AssetManager asset = getResources (). getAssets (); // get assets tool class AssetManager reference
        59. Try {
        60. InputStream inputStream = asset. open ("data.txt"); // input stream of data.txt in assetsdirectory
        61. Int length = inputStream. available (); // obtain the length of readable bytes of the input stream.
        62. Byte [] buffer = new byte [length];
        63. InputStream. read (buffer); // read the buffer byte data from the input stream to the buffer byte array.
        64. String result = new String (buffer, "GB2312"); // converts byte data to String data.
        65. Context. setText (result); // display the data.txt data in the assetsdirectory to the text display box
        66. } Catch (IOException e ){
        67. E. printStackTrace ();
        68. }
        69. Break;
        70. Case R. id. parserRaw:
        71. InputStream inputStream = getResources (). openRawResource (
        72. R. raw. skill); // obtain the input stream in the res/raw directory.
        73. Int length;
        74. Try {
        75. Length = inputStream. available (); // obtain the length of readable bytes of the input stream.
        76. Byte [] buffer = new byte [length];
        77. InputStream. read (buffer); // read the buffer byte data from the input stream to the buffer byte array.
        78. String result = new String (buffer, "GB2312"); // converts byte data to String data.
        79. Context. setText (result); // display the data.txt data in the assetsdirectory to the text display box
        80. Break;
        81. } Catch (IOException e ){
        82. E. printStackTrace ();
        83. }
        84. Case R. id. parserXML:
        85. XmlResourceParser xmlParser = getResources (). getXml (R. xml. persons); // obtain the input stream in the res/xml directory.
        86. Try {
        87. StringBuilder sb = new StringBuilder ();
        88. While (xmlParser. getEventType ()! = XmlPullParser. END_DOCUMENT) {// determine whether to read the XML document.
        89. If (xmlParser. getEventType () = XmlPullParser. START_TAG) {// The start tag is displayed.
        90. String tagName = xmlParser. getName (); // obtain the Tag Name
        91. If (tagName. equals ("person") {// obtain the corresponding Attribute Based on the Tag Name
        92. String personAge = xmlParser. getAttributeValue (null, "age"); // obtain the attribute value based on the attribute name
        93. String personSex = xmlParser. getAttributeValue (1); // obtain the attribute value based on the attribute name
        94. String person = xmlParser. nextText (); // obtain the value of the text node.
        95. String onePerson = "name:" + person + "Gender:" + personSex + "age:" + personAge;
        96. Sb. append (onePerson );
        97. }
        98. Sb. append ("\ n ");
        99. }
        100. XmlParser. next (); // gets the next event of the parser
        101. }
        102. Context. setText (sb. toString ());
        103. } Catch (XmlPullParserException e ){
        104. E. printStackTrace ();
        105. } Catch (IOException e ){
        106. E. printStackTrace ();
        107. }
        108. Break;
        109. Default:
        110. Break;
        111. }
        112. }
        113. }
        114. } The layout file main. xml is as follows:
          1. Xmlns: tools = "http://schemas.android.com/tools"
          2. Android: layout_width = "match_parent"
          3. Android: layout_height = "match_parent"
          4. Android: orientation = "vertical">
          5. Android: layout_width = "fill_parent"
          6. Android: layout_height = "60dp">
          7. Android: id = "@ + id/parserXML"
            • Android: layout_width = "wrap_content"
            • Android: layout_height = "fill_parent"
            • Android: text = "parsing xml"/>
            •  
            Android: id = "@ + id/parserAssets"
            • Android: layout_centerInParent = "true"
            • Android: layout_width = "wrap_content"
            • Android: layout_height = "fill_parent"
            • Android: text = "parsing assets"/>
            •  
            Android: id = "@ + id/parserRaw"
            • Android: layout_alignParentRight = "true"
            • Android: layout_width = "wrap_content"
            • Android: layout_height = "fill_parent"
            • Android: text = "parse raw"/>
            •  
            • Android: layout_width = "fill_parent"
            • Android: layout_height = "fill_parent">
            • Android: id = "@ + id/text"
            • Android: layout_width = "fill_parent"
            • Android: layout_height = "wrap_content"/>
            •  
            • In addition, if we need to obtain all the files and slice resources under the assets Directory, we can do this:
              1. Int currentImage = 0;
              2. InputStream inputStream = null;
              3. AssetManager assetManager = getResources (). getAssets ();
              4. String [] images = assetManager. list (""); // obtain the names of all files in the assets/myImages directory
              5. Public void nextBtn (View v ){
              6. // Prevents array out-of-bounds Processing
              7. If (currentImage> = images. length ){
              8. CurrentImage = 0;
              9. }
              10. // Obtain the corresponding input stream based on the file name
              11. InputStream = assetManager. open (images [currentImage ++]);
              12. // If the image has not been recycled, forcibly recycle the image first.
              13. BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView. getDrawable ();
              14. If (bitmapDrawable! = Null &&! BitmapDrawable. getBitmap (). isRecycled ()){
              15. BitmapDrawable. getBitmap (). recycle ();
              16. }
              17. // Encode the input stream to obtain the image
              18. ImageView. setImageBitmap (BitmapFactory. decodeStream (inputStream ));
              19. // Close the input stream
              20. InputStream. close ();
              21. }
                Summary: public final String [] list (String path) returns the names of all files and subdirectories under the current directory. You can recursively traverse the entire file directory to access all resource files. Access a resource method in the assets subdirectory: String [] list = null; list = getResources (). getAssets (). list ("abc"); it returns a list of file names in the abc folder under the assets folder. Check whether the list contains the files you need. When reading files in the abc folder, you only need to: InputStreamin = getResources (). getAssets (). open ("abc/yan.txt"); obtain the input stream of the file.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.