在 Android 中存储静态数据 - 自定义资源?

发布于 2024-09-08 16:22:23 字数 523 浏览 9 评论 0 原文

我是 Android 开发新手,我已经尝试过一些。我试图创建一个程序,该程序具有一个类似数据库的小型不变数据集合。在我目前最好的语言 C# 中,我将使用自定义类的列表并将其序列化为 xml 文件,然后在运行时将其读入我的应用程序。我在 Android 中找到了 /xml 资源文件夹,但我不确定如何去做我设想的事情。这样做的最佳方法是什么?

数据永远不需要改变。示例:

Blob   | A  | B
----------------
Blob 1 | 23 | 42
Blob 2 | 34 | 21

我知道它的布局就像表格一样,但是使用数据库对我来说并没有真正的意义,因为数据永远不会改变,而且我需要一种方法来存储它以最初填充数据库

所以基本上我正在寻找一种在我的应用程序中存储有些复杂的静态数据的方法。有什么想法吗?

编辑:我还看到了 /raw 文件夹。所以我可以将东西存储在 /res/raw 或 /res/xml 中。但我不确定存储/解析数据的最佳方式是什么......

I'm new to Android development, and I've been playing around with it a bit. I was trying to create a program that has a small database-like collection of never-changing data. In C#, my currently best language, I'd use a List of a custom class and serialize that to an xml file, then read that into my application at runtime. I found the /xml resource folder in Android, but I'm not sure how I would go about doing what I'm envisioning. What would be the best way to go about doing this?

The data will never need to change. Example:

Blob   | A  | B
----------------
Blob 1 | 23 | 42
Blob 2 | 34 | 21

I know that's laid out like a table, but using a database doesn't really make sense to me because the data will never change, and I would need a way to store it to initially populate the database anyway.

So basically I'm looking for a way to store somewhat-complex static data in my application. Any ideas?

EDIT: I also saw the /raw folder. So I could store things in /res/raw or /res/xml. But I'm not sure what would be the best way to store/parse the data...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

¢蛋碎的人ぎ生 2024-09-15 16:22:23

我认为这是最好的解决方案,我已经使用这个解决方案在我的每个项目中存储静态数据。

为此...
您可以做一件事,制作一个 xml 文件,即“temp.xml”..并将数据存储在 temp.xml 中,如下所示:

  <?xml version="1.0" encoding="utf-8"?> 
<rootelement1>

    <subelement> Blob 1  
     <subsubelement> 23 </subsubelement>
     <subsubelement> 42 </subsubelement> 
    </subelement>

    <subelement>Blob 2      
    <subsubelement> 34 </subsubelement>
    <subsubelement> 21 </subsubelement>
    </subelement>


    </rootelement1>

然后使用 XML PullParser 技术来解析数据。
您可以在示例上获得 PullParsing 技术的编码示例,请参考此更好的想法的例子。

享受!!

I think this is the BEST solution and i am already using this one to store Static-data in my every project.

For that...
You can do one thing, make one xml file namely "temp.xml" ..and store the data in temp.xml as follows:

  <?xml version="1.0" encoding="utf-8"?> 
<rootelement1>

    <subelement> Blob 1  
     <subsubelement> 23 </subsubelement>
     <subsubelement> 42 </subsubelement> 
    </subelement>

    <subelement>Blob 2      
    <subsubelement> 34 </subsubelement>
    <subsubelement> 21 </subsubelement>
    </subelement>


    </rootelement1>

and then use XML PullParser technique to parse data.
You can have coding samples of PullParsing technique on Example , refer this example for better idea.

Enjoy!!

如日中天 2024-09-15 16:22:23

最好的方法是使用 Android 资源层次结构

在 res/values/ 目录中,您可以存储多种基本数据类型的任意数量的键值对。在您的应用程序中,您将使用自动生成的资源 ID(基于您的资源密钥的名称)来引用它们。请参阅上面的链接以获取更多文档和详细信息。

Android 还支持原始数据文件。您可以将数据存储在 res/raw/yourfile.dat 下的文件目录中。

您可以以所需的任何基于文本的格式创建数据,然后在活动启动时使用资源访问 api 读取它。

The best way is to use the Android Resource Heirarchy.

In the res/values/ directory, you can store any number of key-value pairs for several basic data types. In your app, you would refer to them using an autogenerated resource id (name based on your resource's key). See the link above for more documentation and details.

Android also supports raw datafiles. You could store your data in the file directory under res/raw/yourfile.dat

You you create your data in whatever text based format you want and then read it on activity startup using the resource access apis.

肩上的翅膀 2024-09-15 16:22:23

我过去曾使用 Simple 进行 xml 解析。我认为如果您知道 xml 中的内容(在您的情况下您知道),那么它的代码量最少。

http://simple.sourceforge.net/

I have used Simple for xml parsing in the past. I think it has the least amount of code if you know what to expect in xml, which in your case you do.

http://simple.sourceforge.net/

烧了回忆取暖 2024-09-15 16:22:23

根据 doc/xml 是可行的方法。

提供资源

xml/ 任意运行时可以通过调用读取的XML文件

Resources.getXML().

各种XML配置文件必须保存在这里,例如可搜索的配置。

getXML() 的文档

我还做了一个工作示例:

  • XML 结构:

    
    <测验问题>
        <测验问题>
            ic_help_black_24dp
            <问题>美国的首都是哪里?
            无线电
            <回答正确=“假”>纽约市
            <回答正确=“true”>华盛顿特区
            <回答正确=“假”>芝加哥
            <回答正确=“假”>费城
        
    
        <测验问题>
            ic_help_black_24dp
            <问题>荷兰著名画家文森特·威廉·范....的姓氏是什么?
            编辑文本              
            <答案正确=“true”>Gogh
        
    
    
  • 保存解析数据的 Java 类:

    公共类 QuizQuestion {
        私有 int headerImageResId;
        私有字符串问题;
        私有字符串输入类型;
        私有ArrayList答案;
        私有ArrayList<布尔值>答案正确;
        私有ArrayList正确答案索引;
    
        /**
         * QuizQuestion 对象的构造函数
         */
        测验问题() {
            headerImageResId = 0;
            问题=空;
            输入类型=空;
            答案 = new ArrayList<>();
            AnswerIsCorrect = new ArrayList<>();
            CorrectAnswerIndexes = new ArrayList<>();
        }
    
    
        公共无效setHeaderImageResId(int headerImageResId){
            this.headerImageResId = headerImageResId;
        }
    
        公共 int getHeaderImageResId() {
            返回 headerImageResId;
        }
    
    
        void setQuestion(字符串问题) {
            this.question = 问题;
        }
    
        公共字符串 getQuestion() {
            返回问题;
        }
    
    
        无效setInputType(字符串输入类型){
            this.inputType = inputType;
        }
    
        公共字符串 getInputType() {
            返回输入类型;
        }
    
        void addAnswer(字符串答案,布尔值是否正确)
        {
            如果(正确)
                CorrectAnswerIndexes.add(answers.size());
            答案.添加(答案);
            answerIsCorrect.add(isCorrect);
        }
    
    
        公共ArrayList<字符串>获取答案() {
            返回答案;
        }
    
        公共字符串 getAnswer(int 索引)
        {
            // 检查索引以避免越界异常
            if (index 
  • 解析器本身:

    <前><代码>/**
    * 由 bivanbi 创建于 2017.02.23..
    *
    * 将包含测验数据的 xml 资源解析为 QuizQuestion 对象的 ArrayList 的类
    *
    */

    公共类 QuizXmlParser {

    公共静态字符串lastErrorMessage =“”;

    /**
    * 将 XML 数据解析为 QuizQuestion 对象的 ArrayList 的静态方法
    * @param Activity 是调用 Activity
    * @param xmlResourceId 为待解析的XML资源的资源id
    * 如果发生解析错误则返回 null,如果成功则返回对象的 ArrayList
    * @抛出XmlPullParserException
    * @抛出IOException
    */
    public static ArrayList;解析(活动活动,int xmlResourceId)
    抛出 XmlPullParserException、IOException
    {
    String logTag = QuizXmlParser.class.getSimpleName();
    资源 res = Activity.getResources();
    XmlResourceParser quizDataXmlParser = res.getXml(R.xml.quiz_data);

    ArrayList<字符串> xmlTagStack = new ArrayList<>();
    ArrayList<测验问题> quizQuestions = new ArrayList<>();

    测验问题当前问题 = null;

    布尔值 isCurrentAnswerCorrect = false;

    quizDataXmlParser.next();
    int eventType = quizDataXmlParser.getEventType();
    while (eventType!= XmlPullParser.END_DOCUMENT)
    {
    // 开始文档
    if(eventType == XmlPullParser.START_DOCUMENT)
    {
    Log.d(logTag,"开始文档");
    }
    // 开始标签
    否则 if(eventType == XmlPullParser.START_TAG)
    {
    字符串 tagName = quizDataXmlParser.getName();
    xmlTagStack.add(tagName);
    Log.d(logTag,"开始标签"+tagName+",深度:"+xmlTagStack.size());
    Log.d(logTag,"标签 "+tagName+" 具有 "+quizDataXmlParser.getAttributeCount()+" 属性");

    // 这是测验问题标签的开始,因此创建一个新的 QuizQuestion 对象
    if (tagName.equals("测验问题")){
    当前问题 = new QuizQuestion();
    }
    else if(tagName.equals("answer"))
    {
    isCurrentAnswerCorrect = quizDataXmlParser.getAttributeBooleanValue(null,"正确",false);
    if (isCurrentAnswerCorrect == true) {
    Log.d(logTag, "标签 " + tagName + " 具有正确属性 = true");
    }
    别的
    {
    Log.d(logTag, "标签 " + tagName + " 具有正确属性 = false");
    }
    }
    }
    // 结束标记
    否则 if(eventType == XmlPullParser.END_TAG)
    {
    字符串 tagName = quizDataXmlParser.getName();
    如果 (xmlTagStack.size() < 1)
    {
    lastErrorMessage = "错误 101: 当 TagStack 为空时遇到 END_TAG "+quizDataXmlParser.getName()+";
    Log.e(logTag, 最后的错误消息);
    返回空值;
    }
    xmlTagStack.remove(xmlTagStack.size()-1);
    Log.d(logTag,"结束标签"+quizDataXmlParser.getName()+", 深度:"+xmlTagStack.size());

    // 到达测验问题定义的末尾,将其添加到数组中
    if (tagName.equals("测验问题")){
    if (当前问题!= null)
    quizQuestions.add(currentQuestion);
    当前问题 = null;
    }
    }
    // 标签开始和结束之间的文本
    else if(eventType == XmlPullParser.TEXT)
    {
    字符串 currentTag = xmlTagStack.get(xmlTagStack.size()-1);
    字符串文本 = quizDataXmlParser.getText();
    Log.d(logTag,"文本:"+text+",当前标签:"+currentTag+",深度:"+xmlTagStack.size());

    if (当前问题 == null) {
    Log.e(logTag,"currentQuestion未初始化!text:"+text+",当前标签:"+currentTag+",深度:"+xmlTagStack.size());
    继续;
    }

    if (currentTag.equals("header_image_src"))
    {
    int drawableResourceId = Activity.getResources().getIdentifier(text, "drawable", Activity.getPackageName());
    currentQuestion.setHeaderImageResId(drawableResourceId);
    }
    else if (currentTag.equals("问题"))
    {
    currentQuestion.setQuestion(文本);
    }
    else if (currentTag.equals("answer"))
    {
    currentQuestion.addAnswer(text, isCurrentAnswerCorrect);
    }
    else if (currentTag.equals("input_type"))
    {
    currentQuestion.setInputType(文本);
    }
    别的
    {
    Log.e(logTag,"意外标签"+currentTag+",文本:"+text+",深度:"+xmlTagStack.size());
    }
    }
    eventType = quizDataXmlParser.next();
    }
    Log.d(logTag,"结束文档");
    返回测验问题;
    }

    }

  • 最后,调用解析器:

    //从xml资源quiz_data读取测验数据
    尝试 {
        quizQuestions = QuizXmlParser.parse(this,R.xml.quiz_data);
        Log.d("主要","测验问题:"+测验问题);
    
    } catch (XmlPullParserException e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
        测验问题=空;
    } catch (IOException e) {
        // TODO 自动生成的 catch 块
        e.printStackTrace();
        测验问题=空;
    }
    
    if (测验问题 == null)
    {
        Toast.makeText(this,"1001 无法解析测验 XML,抱歉", Toast.LENGTH_LONG).show();
        结束();
    }
    

According to the doc, /xml is the way to go.

Providing Resources

xml/ Arbitrary XML files that can be read at run-time by calling

Resources.getXML().

Various XML configuration files must be saved here, such as a searchable configuration.

Documentation for getXML()

I also made a working example:

  • the XML structure:

    <?xml version="1.0" encoding="utf-8"?>
    <quizquestions>
        <quizquestion>
            <header_image_src>ic_help_black_24dp</header_image_src>
            <question>What is the Capital of U.S.A.?</question>
            <input_type>Radio</input_type>
            <answer correct="false">New York City</answer>
            <answer correct="true">Washington D.C.</answer>
            <answer correct="false">Chicago</answer>
            <answer correct="false">Philadelphia</answer>
        </quizquestion>
    
        <quizquestion>
            <header_image_src>ic_help_black_24dp</header_image_src>
            <question>What is the family name of the famous dutch painter Vincent Willem van .... ?</question>
            <input_type>EditText</input_type>              
            <answer correct="true">Gogh</answer>
        </quizquestion>
    </quizquestions>
    
  • the Java class to hold parsed data:

    public class QuizQuestion {
        private int headerImageResId;
        private String question;
        private String inputType;
        private ArrayList<String> answers;
        private ArrayList<Boolean> answerIsCorrect;
        private ArrayList<Integer> correctAnswerIndexes;
    
        /**
         * constructor for QuizQuestion object
         */
        QuizQuestion() {
            headerImageResId = 0;
            question = null;
            inputType = null;
            answers = new ArrayList<>();
            answerIsCorrect = new ArrayList<>();
            correctAnswerIndexes = new ArrayList<>();
        }
    
    
        public void setHeaderImageResId(int headerImageResId) {
            this.headerImageResId = headerImageResId;
        }
    
        public int getHeaderImageResId() {
            return headerImageResId;
        }
    
    
        void setQuestion(String question) {
            this.question = question;
        }
    
        public String getQuestion() {
            return question;
        }
    
    
        void setInputType(String inputType) {
            this.inputType = inputType;
        }
    
        public String getInputType() {
            return inputType;
        }
    
        void addAnswer(String answer, boolean isCorrect)
        {
            if (isCorrect)
                correctAnswerIndexes.add(answers.size());
            answers.add(answer);
            answerIsCorrect.add(isCorrect);
        }
    
    
        public ArrayList<String> getAnswers() {
            return answers;
        }
    
        public String getAnswer(int index)
        {
            // check index to avoid out of bounds exception
            if (index < answers.size()) {
                return answers.get(index);
            }
            else
            {
                return null;
            }
        }
    
        public int size()
        {
            return answers.size();
        }
    
    }
    
  • the parser itself:

    /**
     * Created by bivanbi on 2017.02.23..
     *
     * class to parse xml resource containing quiz data into ArrayList of QuizQuestion objects
     *
     */
    
    public class QuizXmlParser {
    
        public static String lastErrorMessage = "";
    
        /**
         * static method to parse XML data into ArrayList of QuizQuestion objects
         * @param activity is the calling activity
         * @param xmlResourceId is the resource id of XML resource to be parsed
         * @return null if parse error is occurred or ArrayList of objects if successful
         * @throws XmlPullParserException
         * @throws IOException
         */
        public static ArrayList<QuizQuestion> parse(Activity activity, int xmlResourceId)
                throws XmlPullParserException, IOException
        {
            String logTag = QuizXmlParser.class.getSimpleName();
            Resources res = activity.getResources();
            XmlResourceParser quizDataXmlParser = res.getXml(R.xml.quiz_data);
    
            ArrayList<String> xmlTagStack = new ArrayList<>();
            ArrayList<QuizQuestion> quizQuestions = new ArrayList<>();
    
            QuizQuestion currentQuestion = null;
    
            boolean isCurrentAnswerCorrect = false;
    
            quizDataXmlParser.next();
            int eventType = quizDataXmlParser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT)
            {
                //  begin document
                if(eventType == XmlPullParser.START_DOCUMENT)
                {
                    Log.d(logTag,"Begin Document");
                }
                //  begin tag
                else if(eventType == XmlPullParser.START_TAG)
                {
                    String tagName = quizDataXmlParser.getName();
                    xmlTagStack.add(tagName);
                    Log.d(logTag,"Begin Tag "+tagName+", depth: "+xmlTagStack.size());
                    Log.d(logTag,"Tag "+tagName+" has "+quizDataXmlParser.getAttributeCount()+" attribute(s)");
    
                    // this is a beginning of a quiz question tag so create a new QuizQuestion object
                    if (tagName.equals("quizquestion")){
                        currentQuestion = new QuizQuestion();
                    }
                    else if(tagName.equals("answer"))
                    {
                        isCurrentAnswerCorrect = quizDataXmlParser.getAttributeBooleanValue(null,"correct",false);
                        if (isCurrentAnswerCorrect == true) {
                            Log.d(logTag, "Tag " + tagName + " has attribute correct = true");
                        }
                        else
                        {
                            Log.d(logTag, "Tag " + tagName + " has attribute correct = false");
                        }
                    }
                }
                //  end tag
                else if(eventType == XmlPullParser.END_TAG)
                {
                    String tagName = quizDataXmlParser.getName();
                    if (xmlTagStack.size() < 1)
                    {
                        lastErrorMessage = "Error 101: encountered END_TAG "+quizDataXmlParser.getName()+" while TagStack is empty";
                        Log.e(logTag, lastErrorMessage);
                        return null;
                    }
                    xmlTagStack.remove(xmlTagStack.size()-1);
                    Log.d(logTag,"End Tag "+quizDataXmlParser.getName()+", depth: "+xmlTagStack.size());
    
                    //  reached the end of a quizquestion definition, add it to the array
                    if (tagName.equals("quizquestion")){
                        if (currentQuestion != null)
                            quizQuestions.add(currentQuestion);
                        currentQuestion = null;
                    }
                }
                //  text between tag begin and end
                else if(eventType == XmlPullParser.TEXT)
                {
                    String currentTag = xmlTagStack.get(xmlTagStack.size()-1);
                    String text = quizDataXmlParser.getText();
                    Log.d(logTag,"Text: "+text+", current tag: "+currentTag+", depth: "+xmlTagStack.size());
    
                    if (currentQuestion == null) {
                        Log.e(logTag,"currentQuestion is not initialized! text: "+text+", current tag: "+currentTag+", depth: "+xmlTagStack.size());
                        continue;
                    }
    
                    if (currentTag.equals("header_image_src"))
                    {
                        int drawableResourceId = activity.getResources().getIdentifier(text, "drawable", activity.getPackageName());
                        currentQuestion.setHeaderImageResId(drawableResourceId);
                    }
                    else if (currentTag.equals("question"))
                    {
                        currentQuestion.setQuestion(text);
                    }
                    else if (currentTag.equals("answer"))
                    {
                        currentQuestion.addAnswer(text, isCurrentAnswerCorrect);
                    }
                    else if (currentTag.equals("input_type"))
                    {
                        currentQuestion.setInputType(text);
                    }
                    else
                    {
                        Log.e(logTag,"Unexpected tag "+currentTag+" with text: "+text+", depth: "+xmlTagStack.size());
                    }
                }
                eventType = quizDataXmlParser.next();
            }
            Log.d(logTag,"End Document");
            return quizQuestions;
        }
    
    }
    
  • and finally, calling the parser:

    //  read quiz data from xml resource quiz_data
    try {
        quizQuestions = QuizXmlParser.parse(this,R.xml.quiz_data);
        Log.d("Main","QuizQuestions: "+quizQuestions);
    
    } catch (XmlPullParserException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        quizQuestions = null;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        quizQuestions = null;
    }
    
    if (quizQuestions == null)
    {
        Toast.makeText(this,"1001 Failed to parse Quiz XML, sorry", Toast.LENGTH_LONG).show();
        finish();
    }
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文