Android basics 23: Android reads files from assets and res

Source: Internet
Author: User
Tags getcolor html encode xml attribute xml example java reference

This section describes the file formats of assets and res in Android and how to obtain the file content. The file size limits of assets and raw folders and solutions are also described.

1. Introduction to related folders

In the android project folder, the main resource files are stored in the res folder. The assets folder is a native file that is not compiled and processed, that is, the files in this folder are not like XML, java files are pre-compiled, and some images, HTML, JS, CSS files. The following describes how to read Resources in the assets folder!

Introduction of Multiple folders in the res folder (from the Chinese version of the android Development Guide on the Internet ):

Directory directory Resource types
Res/anim/ XML files, which are compiled into frame by frame animation or tweened animation objects.
Res/drawable/ .Png0000.9.png0000.jpg files, which are compiled into the following drawable resource subtype:
To obtain a resource of this type, you can use resource. getdrawable (ID)
Bitmap files
9-patches (bitmap with variable size)
To obtain the resource type, use mcontext. getresources (). getdrawable (R. drawable. imageid)
Note: image resources stored here may be automatically subjected to lossless compression optimization by the aapt tool. For example, a PNG with a true color but no 256 color is required may be converted into an 8-bit PNG with a color palette. This allows images of the same quality to consume less resources. So we must realize that these binary images placed in this directory may change during production. If you want to read an image bit stream and convert it into a bitmap, put the image file in the Res/raw/directory to avoid automatic optimization.
Res/layout/ XML file compiled as a screen layout (or part of the screen. See declaring Layout)
Res/values/ It can be compiled into XML files of many types of resources.
Note: unlike other RES/folders, it can save any number of files that save the description of the resource to be created, rather than the resource itself. The XML Element type controls where these resources should be placed in the r class.
Although the files in this folder can be named arbitrarily, some typical files are used below (the naming convention of a file is to include the element type in the name ):
Array. xml defines an array
Colors. xml defines the color drawable and color string values (color string values ). Use resource. getdrawable () and resources. getcolor () to obtain these resources respectively.
Dimens. xml defines the dimension value ). Use resources. getdimension () to obtain these resources.
Strings. xml defines the string value. Use resources. getstring () or resources. gettext () to obtain these resources. Gettext () retains the Rich Text styles applied on the UI string.
Styles. xml defines the style object.
Res/XML/ Any XML file can be read by calling resources. getxml () at runtime.
Res/raw/ Copy directly to any file on the device. They do not need to be compiled and are added to the compressed files generated by your application compilation. To use these resources, you can call resources. openrawresource (). The parameter is the resource ID, that is, R. Raw. somefilename.

2. automatically generated R class
There is an R. Java in the gen folder of the project folder. The resources we usually Reference Mainly reference the variables of this class.
 
Note: The R class is automatically generated and cannot be manually modified. It is automatically modified when the resource changes.
 
3. Use RESOURCES IN CODE
The following is a resource reference Syntax:
R. resource_type.resource_name or android. R. resource_type.resource_name
 
Resource_type is a subclass of R and stores a specific type of resource. Objects, name = icon ). Android contains many standard resources, such as screen styles and button backgrounds. To reference these resources in the code, you must use Android for limitation, such as Android. R. drawable. button_background.
 
Below are some official examples of correct and incorrect usage of compiled resources in code:

// Load a background for the current screen from a drawable resource. this.getWindow().setBackgroundDrawableResource(R.drawable.my_background_image);  // WRONG Sending a string resource reference into a  // method that expects a string. this.getWindow().setTitle(R.string.main_title);  // RIGHT Need to get the title from the Resources wrapper. this.getWindow().setTitle(Resources.getText(R.string.main_title));  // Load a custom layout for the current screen. setContentView(R.layout.main_screen);  // Set a slide in animation for a ViewFlipper object. mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,          R.anim.hyperspace_in));  // Set the text on a TextView object. TextView msgTextView = (TextView)findViewByID(R.id.msg); msgTextView.setText(R.string.hello_message);  

I checked the SDK Doc to see why window. resources. gettext. The original settitle parameter is charsequence, resources. gettext (INT) returns charsequence, while other settext parameters include charsequence and INT (this is the value of the resources variable ).
 
At the same time, two examples of using system resources are also officially provided:

// Display the public class myactivity extends activity {public void onstart () {requestscreenfeatures (feature_badge_image); super. onstart (); setbadgeresource (Android. r. drawable. sym_def_app_icon) ;}// the standard "green background" defined by the application system for visual processing of public class myactivity extends activity public void onstart () {super. onstart (); settheme (Android. r. style. theme_black );}}

4. Reference resources in the XML file
1) Reference custom Resources
Android: text = "@ string/hello"
Here, we use the "@" prefix to introduce a reference to a resource. In the @ [Package:] type/name format, the following text is the name of the resource. In this case, we do not need to specify the package name, because we reference the resources in our own package. Type is the XML subnode name, and name is the XML Attribute Name:

<?xml version="1.0" encoding="utf-8"?> <resources>     <string name="hello">Hello World, HelloDemo!</string> </resources>

2) Reference System Resources
Android: textcolor = "@ Android: color/opaque_red" specify package: Android
 
3) Reference topic attributes
Another resource value allows you to reference the attribute values in the current topic. This attribute value can only be used in style resources and XML attributes. It allows you to change the appearance of the UI element by changing them to the standard changes provided by the current topic, rather than providing specific values.
Android: textcolor = "? Android: textdisabledcolor"

Note that this is very similar to resource reference, except that we use "? "Prefix replaces "@". When you use this tag, you provide the name of the property resource, which will be searched in the topic-because the resource tool knows the required property resource, therefore, you do not need to display the Declaration type (if the declaration is in the form? Android: ATTR/Android: textdisabledcolor ). Besides using the resource identifier to query the value in the topic instead of the original resource, the naming syntax is the same as that in the "@" Format :? [Namespace:] type/name. The type is optional.
 
5. replace resources (for Replaceable Resources and configurations)
I personally understand that this replacement resource is mainly used to adapt to a variety of screen specifications and internationalization. For more information, see http://androidappdocs.appspot.com/guide/topics/resources/resources-i18n.html!
 
6. color value
Syntax:

<color name="color_name">#color_value</color> 

It can be stored in RES/values/colors. XML (the file name can be arbitrary ).
XML reference: Android: textcolor = "@ color/color_name"
Java reference: int color = resources. getcolor (R. color. color_name)
 
Where # color_value has the following format (A represents the alpha channel ):
# RGB
# Argb
# Rrggbb
# Aarrggbb
 
XML example (declare two colors, the first is not transparent, and the second is transparent ):

<?xml version="1.0" encoding="utf-8"?> <resources>     <color name="opaque_red">#f00</color>     <color name="translucent_red">#80ff0000</color> </resources> 

7. Color drawables
Syntax:

<drawable name="color_name">color_value</drawable>

It can be saved in RES/values/colors. xml.
XML reference: Android: Background = "@ drawable/color_name"
Java reference: drawable reddrawable = resources. getdrawable (R. drawable. color_name)
 
Color_name is the same as above. In my opinion, the color attribute is generally used, and the drawable attribute is used only when paintdrawable is used.
 
XML example:

<?xml version="1.0" encoding="utf-8"?> <resources>     <drawable name="opaque_red">#f00</drawable>     <drawable name="translucent_red">#80ff0000</drawable> </resources> 

8. Images
It is generally placed in RES/drawable. Official tips: PNG (preferred), JPG (acceptable), and GIF (discouraged). It seems that the PNG format is better!
XML reference @ [Package:] drawable/some_file
Java references the R. drawable. some_file reference without the extension
 
9. Dimension
Syntax:

<Dimen name = "dimen_name"> dimen_value Unit </dimen>

It is generally stored as res/values/dimen. xml.
Measurement unit:
Px (pixel): The actual pixel of the screen. The resolution is usually 1024*768 pixels, that is, 1024px in the horizontal direction and 768px in the vertical direction. Different devices have the same display effect.
 
In (INCHES): the physical size of the screen. each inch equals 2.54 cm.
 
Mm (mm): physical size of the screen.
 
Pt (point): physical size of the screen. 1/72 inch.
 
DP/dip: density-independent pixel, an abstract unit based on screen density. 1dp = 1px on a display at 160 o'clock per inch. However, the ratio of DP to PX varies with the screen density, and different devices have different display effects.
 
SP: pixel irrelevant to the scale. It is mainly used to display the best for textsize in the font, and is used as the unit of size related to the text.
 
XML: Android: textsize = "@ dimen/some_name"
Java: Float dimen = resources. getdimen (R. dimen. some_name)
 
XML example:

<?xml version="1.0" encoding="utf-8"?> <resources>     <dimen name="one_pixel">1px</dimen>     <dimen name="double_density">2dp</dimen>     <dimen name="sixteen_sp">16sp</dimen> </resources> 

10. String
The following is an official correct/incorrect example:

// If the escape character is not used, double quotation marks must be used to enclose the entire string <string name = "good_example"> "this'll work" </string> // use the Escape Character <string name = "good_example_2"> This \'ll also work </string> // error <string name = "bad_example"> This won't work! </String> // error cannot use HTML Escape characters <string name = "bad_example_2"> XML encodings won't work either! </String>

For formatted strings, for example, to set the color of some characters in the string, you can use HTML tags. Some processing is required for this type of string, which cannot be referenced by other resources in XML. An official example is provided to compare the use of common and formatted strings:

<?xml version="1.0" encoding="utf-8"?> <resources>     <string name="simple_welcome_message">Welcome!</string>     <string name="styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string> </resources> 

XML Code

<TextView     android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:textAlign="center"     android:text="@string/simple_welcome_message"/> 

Java code

// Assign a styled string resource to a TextView on the current screen. CharSequence str = getString(R.string.styled_welcome_message); TextView tv = (TextView)findViewByID(R.id.text); tv.setText(str); 

In addition, it is a little effort to process strings with style/format. An official example is provided:

<?xml version="1.0" encoding="utf-8"?> <resources>   <string name="search_results_resultsTextFormat">%1$d results for <b>&quot;%2$s&quot;</b></string> </resources> 

Here, % 1 $ D is a decimal number, and % 2 $ S is a string. Before assigning a string to % 2 $ S, you need to use the htmlencode (string) function to process the string:

// Title is the string escapedtitle = textutil.html encode (title) that we want to assign to % 2 $ s, and then use string. format () to assign values, and then use fromhtml (string) to get the formatted string: String resultstextformat = getcontext (). getresources (). getstring (R. string. search_results_resultstextformat); string resultstext = string. format (resultstextformat, Count, escapedtitle); charsequence styledresults = html. fromhtml (resultstext );

11. Access to assets folder Resources
All files in the assets folder are in the original file format. You need to use assetmanager to read files in the form of byte streams.
1. Call getassets () in the activity to obtain the assetmanager reference.
2. Use assetmanager's open (string filename, int accessmode) method to specify the file to be read and the access mode to obtain the input stream inputstream.
3. Use inputstream of the open file to read the file. After reading the file, remember inputstream. Close ().
4. Call assetmanager. Close () to close assetmanager.
Note that files from resources and assets can only be read but cannot be written.
Read from raw files as follows:
Code

public String getFromRaw(){             try {                 InputStreamReader inputReader = new InputStreamReader( getResources().openRawResource(R.raw.test1));                BufferedReader bufReader = new BufferedReader(inputReader);                String line="";                String Result="";                while((line = bufReader.readLine()) != null)                    Result += line;                return Result;            } catch (Exception e) {                 e.printStackTrace();             }                 } 

Read from assets directly
Code

public String getFromAssets(String fileName){             try {                  InputStreamReader inputReader = new InputStreamReader( getResources().getAssets().open(fileName) );                 BufferedReader bufReader = new BufferedReader(inputReader);                String line="";                String Result="";                while((line = bufReader.readLine()) != null)                    Result += line;                return Result;            } catch (Exception e) {                 e.printStackTrace();             }    } 

Of course, if you want to get the memory stream, you can also directly return the memory stream!

12. Res/raw and assets file size restrictions

The Android system limits the size of resource files (in the Res/raw and assets folders). By default, only 1 MB of files are supported. Otherwise, the APK program reports an error. If assetmanager or resources classes method is used to obtain inputstream, a java. Io. ioexception is thrown as follows: Debug/asset (1123): Data exceeds uncompress_data_max.
Solution to 12.1 large files
1. Change the suffix of your resource file to aapt to ignore the suffix of the compressed file.
2. Use the-0 parameter on the command line to specify the file suffix that does not require compression. For detailed configuration, see the aapt help documentation.
3. Divide the resource file into multiple files smaller than uncompress_data_max (1 m) and combine them in the program.
12.2 aapt compression ignore file description
The aapt tool compresses the resource file to reduce the size of the APK file when packaging the APK file. View the package. cpp source code in the aapt tool and find that some files are not compressed:

/* these formats are already compressed, or don't compress well */   static const char* kNoCompressExt[] = {   ".jpg", ".jpeg", ".png", ".gif",   ".wav", ".mp2", ".mp3", ".ogg", ".aac",   ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet",   ".rtttl", ".imy", ".xmf", ".mp4", ".m4a",   ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2",   ".amr", ".awb", ".wma", ".wmv"   };

References:

Android reads files from assets and res
Res/raw and assets file size restrictions for Android Problems

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.