Domanda

Sono nuovo di sviluppo di Android, e ho giocato intorno con esso un po '. Stavo cercando di creare un programma che ha una piccola collezione di database-like dei dati immutabile. In C #, il mio momento migliore lingua, mi piacerebbe utilizzare un elenco di una classe personalizzata e serializzare che in un file XML, quindi leggere che nella mia applicazione in fase di esecuzione. Ho trovato la cartella delle risorse / xml in Android, ma non sono sicuro di come vorrei andare a fare quello che sto Envisioning. Quale sarebbe il modo migliore per andare a fare questo?

I dati non avrà mai bisogno di cambiare. Esempio:

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

Lo so che è disposto come un tavolo, ma utilizzando un database in realtà non ha senso per me perché i dati non cambieranno mai, e mi avrebbe bisogno di un modo per conservarlo per popolare inizialmente il database in ogni caso .

Quindi, fondamentalmente sto cercando un modo per memorizzare i dati statici po 'complessi nella mia applicazione. Tutte le idee?

EDIT: ho visto anche la cartella / crudo. Così ho potuto memorizzare le cose in / res / raw o / res / xml. Ma io non sono sicuro di quello che sarebbe il modo migliore per conservare / analizzare i dati ...

È stato utile?

Soluzione

Il modo migliore è quello di utilizzare la Android Resource Gerarchia .

Nella / Valori / directory res, è possibile memorizzare un numero qualsiasi di coppie chiave-valore per i diversi tipi di dati di base. Nella vostra applicazione, si dovrebbe fare riferimento a loro utilizzando un ID risorsa generata automaticamente (nome basato sulla chiave di risorsa). Vedi il link qui sopra per ulteriori dettagli e la documentazione.

Android supporta anche file di dati grezzi. Si potrebbe memorizzare i dati nella directory dei file sotto res / raw / yourfile.dat

Si crei i tuoi dati in qualunque formato testo base che si desidera e poi leggerlo all'avvio di attività utilizzando le API di accesso alle risorse.

Altri suggerimenti

Credo che questa sia la soluzione migliore e sto già usando questo per memorizzare i dati statici-in ogni mio progetto.

Per questo ... Si può fare una cosa, fare un file xml e cioè "Temp.xml" ..e memorizzare i dati in Temp.xml come segue:

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

e quindi utilizzare XML PullParser tecnica per i dati analizzare. Si possono avere codifica campioni di tecnica PullParsing su Esempio , consultare questo ad esempio per una migliore idea.

Godetevi !!

ho usato semplice per XML parsing in passato. Penso che abbia la minor quantità di codice se si sa cosa aspettarsi in xml, che nel tuo caso si fa.

http://simple.sourceforge.net/

Secondo il doc , /xml è la strada da percorrere.

fornendo risorse

xml/ arbitraria file XML che possono essere letti a run-time chiamando

Resources.getXML().

I vari file di configurazione XML deve essere salvato qui, come ad esempio una configurazione ricercabile.

Documentazione per getXML()

Ho fatto anche un esempio di lavoro:

  • la struttura XML:

    <?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>
    
  • la classe Java per tenere analizzato i dati:

    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();
        }
    
    }
    
  • il parser stesso:

    /**
     * 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;
        }
    
    }
    
  • e, infine, chiamando il 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();
    }
    
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top