Android uses other resources

Source: Internet
Author: User
1. Use any XML Resource

The XML file to be read is stored in the/RES/XML subdirectory.

For example:/RES/XML/test. xml

<rootelem1><subelem1>Hello World</subelem1></rootelem1>

Read XML files:

Resources res = activity.getResources();XmlResourceParser xpp = res.getXml(R.xml.test);

Use xmlpullparser:

private String getEventsFromXMLFile(Activity activity) throws XmlPullParserException, IOException{StringBuffer sb = new StringBuffer();Resources res = activity.getResources();XmlResourceParser xpp = res.getXml(R.xml.test);xpp.next();int eventType = xpp.getEventType();while(eventType != XmlPullParser.END_DOCUMENT){if(eventType == XmlPullParser.START_DOCUMENT){sb.append("**Start document");}else if(eventType == XmlPullParser.START_TAG){sb.append("\nStart tag "+xpp.getName());}else if(eventType == XmlPullParser.END_TAG){sb.append("\nEnd tag "+xpp.getName());}else if(eventType == XmlPullParser.TEXT){sb.append("\nText "+xpp.getText());}eventType = xpp.next();}sb.append("\n**End document");return sb.toString();}

2. Use Original Resources

Raw resources are located in/RES/raw. These resources are not compiled and transferred to the application package as they are.

For example:/RES/raw/test.txt

Read Original Resources:

String getStringFromRawFile(Activity activity) throws IOException{Resources r = activity.getResources();InputStream is = r.openRawResource(R.raw.test);ByteArrayOutputStream baos = new ByteArrayOutputStream();int i = is.read();while(i != -1){baos.write(i);i = is.read();}String myText = baos.toString();is.close();return myText;}

3. Assets used

/Assets are not included in the/RES file, so files in the asset do not generate R. resource ID in Java. You must specify the file path to read them. The file path is the relative path starting with/assets.

You can use the assetmanager class to access these files.

AssetManager am = activity.getAssets();InputStream is = am.open("test.txt");
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.