Android: reading files under assets directory (2)

In the last blog, I introduced how to read the txt file in the assets directory. Here, I show you how to read an xml file.

The contents of the xml file are as follows:

<?xml version="1.0" encoding="UTF-8"?> 
<books> 
   <book id="001"> 
      <title>Harry Potter</title> 
      <price>¥35.00</price> 
   </book> 
   <book id="002"> 
      <title>Learning XML</title> 
      <price>¥66.00</price> 
   </book> 
   <book id="003"> 
      <title>Thinking in Java</title> 
      <price>¥1.00</price> 
   </book> 
   <book id="004"> 
      <title>Useful Android</title> 
      <price>¥1.50</price> 
   </book> 
</books> 

According to the xml file, next define a Book class, which has three attributes: ID, title and price.

Then a sub thread is used to read the data stream through AssetManager, and XmlPullParser is used to parse the xml file.

The complete example code is as follows:

package com.li.readassetfile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.content.res.AssetManager;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.os.Handler;
import android.util.Xml;
import android.widget.TextView;

public class ReadXmlActivity extends Activity {

    private TextView tvContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_xml);

        tvContent = (TextView) findViewById(R.id.tvContent);

        new Handler().post(new Runnable() {

            @Override
            public void run() {
                AssetManager manager = getResources().getAssets();
                List<Book> books = null;  
                Book book = null;

                try {
                    InputStream inputStream = manager.open("book.xml");  
                    XmlPullParser parser = Xml.newPullParser();  
                    parser.setInput(inputStream, "UTF-8"); 

                    StringBuilder sb = new StringBuilder();

                    try {
                        while(parser.getEventType() != XmlPullParser.END_DOCUMENT){
                            if(parser.getEventType() == XmlPullParser.START_DOCUMENT){

                                books = new ArrayList<ReadXmlActivity.Book>();

                            }else if(parser.getEventType() == XmlPullParser.START_TAG){

                                if("book".equals(parser.getName())){
                                    book = new Book();
                                    book.setId(parser.getAttributeValue(0));
                                }

                                if(book!=null){  
                                    if("title".equals(parser.getName())){//Determine whether the start tag element is name  
                                        book.setTitle(parser.nextText());  
                                    }else if("price".equals(parser.getName())){//Determine whether the start tag element is price  
                                        book.setPrice(parser.nextText());  
                                    }  
                                }  

                            }else if(parser.getEventType() == XmlPullParser.END_TAG){
                                if("book".equals(parser.getName())){//Determine whether the end tag element is a book  
                                    books.add(book);//Add books to the books collection  
                                    book = null;  
                                }  
                            }
                            parser.next();
                        }

                        if(books != null && books.size() > 0){                          
                            for(int i = 0; i < books.size(); i ++){
                                sb.append(books.get(i).getId() + "\b\b");
                                sb.append(books.get(i).getTitle() + "\b\b");
                                sb.append(books.get(i).getPrice() + "\b\b");
                                sb.append("\n");
                            }
                        }

                        inputStream.close();
                        tvContent.setText(sb.toString());
                    } catch (XmlPullParserException e) {
                        e.printStackTrace();
                    }
                } catch (IOException | XmlPullParserException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private class Book{

        private String id;
        private String title;
        private String price;

        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getTitle() {
            return title;
        }
        public void setTitle(String title) {
            this.title = title;
        }
        public String getPrice() {
            return price;
        }
        public void setPrice(String price) {
            this.price = price;
        }
    }
}

After use, pay attention to closing the data flow. In order to prevent ANR, the sub thread is used here to read the xml file.

Tags: xml Android Java encoding

Posted on Tue, 05 May 2020 03:07:07 -0700 by Hobgoblin11