Where to place an XML file containing data within

2019-02-06 01:30发布

问题:

I am new to Android development. I have an XML file with data that the app will read. Where should I keep this XML file? Should it be stored within the "value" folder?

回答1:

I'd say that depends. What do you save in your XML-File? There also is a res/xml-folder, where XML-Files can be kept. But Android does nearly anything with XML-Files, so you might want to read my little Tutorial about where to put which recourses.

Also, there is a difference between the assets and the res-directory's:

res

  • No subdirectorys are allowed under the specific resource-folders.
  • The R-class indexes all resources and provides simple access.
  • There are some simple methods which help reading files stored in the res-directory

assets

  • Subdirectorys are allowed (as much as you like).
  • No indexing by the R-class
  • Reading resources stored in assets is done using the AssetManager.


回答2:

You can put it in the res/raw folder. Then you will access it using:

getResources().openRawResource(resourceName)


回答3:

I had a similar requirement and after lot of research , I found 2 solution to place a custom XML : You can place custom XML in

  1. res/raw/

  2. res/xml/

To access these location you will use following code :

a. if XML is placed in res/raw then :

getResources().openRawResource(R.raw.custom-xml) :

This gives you easy methods for reading xml :

with below code I am reading XML in memory placed in raw folder :


BufferedReader br = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.custom-xml)));

StringBuilder str = new StringBuilder();
String line;
while ( (line = br.readLine()) != null){
    str.append(line);
}

2nd Option :

getResources().openRawResource(R.xml.custom-xml);

with this you could read the xml using eventbased parser.