Where to place an XML file containing data within an Android app

前端 未结 3 624
南旧
南旧 2020-12-31 04:34

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?<

相关标签:
3条回答
  • 2020-12-31 05:03

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

    getResources().openRawResource(resourceName)
    
    0 讨论(0)
  • 2020-12-31 05:06

    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.
    0 讨论(0)
  • 2020-12-31 05:11

    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().getxml(R.xml.custom-xml);

    with this you could read the xml using eventbased parser.

    0 讨论(0)
提交回复
热议问题