HTML in string resource?

后端 未结 6 1001
有刺的猬
有刺的猬 2020-11-28 02:32

I know I can put escaped HTML tags in string resources. However, looking at the source code for the Contacts application I can see that they have a way of not having to enco

6条回答
  •  一整个雨季
    2020-11-28 03:22

    Idea: put the HTML in JSON-formatted files and store them in /res/raw. (JSON is less picky)

    Store the data records like this in an array object:

    [
        {
            "Field1": "String data",
            "Field2": 12345,
            "Field3": "more Strings",
            "Field4": true
        },
        {
            "Field1": "String data",
            "Field2": 12345,
            "Field3": "more Strings",
            "Field4": true
        },
        {
            "Field1": "String data",
            "Field2": 12345,
            "Field3": "more Strings",
            "Field4": true
        }
    ]
    

    To read the data in your app :

    private ArrayList getData(String filename) {
        ArrayList dataArray = new ArrayList();
    
        try {
            int id = getResources().getIdentifier(filename, "raw", getPackageName());
            InputStream input = getResources().openRawResource(id);
            int size = input.available();
            byte[] buffer = new byte[size];
            input.read(buffer);
            String text = new String(buffer);
    
            Gson gson = new Gson();
            Type dataType = new TypeToken>>() {}.getType();
            List> natural = gson.fromJson(text, dataType);
    
            // now cycle through each object and gather the data from each field
            for(Map json : natural) {
                final Data ad = new Data(json.get("Field1"), json.get("Field2"),  json.get("Field3"), json.get("Field4"));
                dataArray.add(ad);
            }
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        return dataArray;
    }
    

    Finally, the Data class is just a container of public variables for easy access...

    public class Data {
    
        public String string;
        public Integer number;
        public String somestring;
        public Integer site;
        public boolean logical;
    
    
        public Data(String string, Integer number, String somestring, boolean logical)
        {
            this.string = string;
            this.number = number;
            this.somestring = somestring;
            this.logical = logical;
        }
    }
    

提交回复
热议问题