Android: Filling a table from resource file using xml (SQLite)

Last time I posted an article on how to fill a table with the help of a string array in a resource file:
Android Filling a table from resource file using string array (SQLite)
The drawback of that technique was that you could only import simple records. So this time I want to show you how to fill a table with complex records (multiple fields).

The XML file

I will use plain xml as a resource file. This gives me the option to enter records and multiple field values for each record.
The xml will be formatted by using one tag for each record and I will use the tag attributes for field values.

Our resource file: res/xml/animals_records.xml

<?xml version="1.0" encoding="utf-8"?>
<animals>
 	<record title="Dog" color="Brown" />
	<record title="Cat" color="Gray" />
	<record title="Rabbit" color="White" />
	<record title="Spider" color="Black" />
</animals>

As you can see I made a xml with records of animals. For every animal I specified the title and color, so thats two fields. You can add as many fields as you want.

Creating the database

We will be using a SQLiteOpenHelper to create/update the database.

/**
 * This class helps open, create, and upgrade the database file.
 */
private static class DatabaseHelper extends SQLiteOpenHelper {
	
	private final Context fContext;
	
	DatabaseHelper(Context context) {
		super(context, "sampledb", null, 1);
		fContext = context;
	} 

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE animals ("
				+ "_id INTEGER PRIMARY KEY,"
				+ "title TEXT,"
				+ "color TEXT"
				+ ");");

		//Add default records to animals
		ContentValues _Values = new ContentValues();        	                
		//Get xml resource file
		Resources res = fContext.getResources();
       	
		//Open xml file
		XmlResourceParser _xml = res.getXml(R.xml.animals_records);
		try
		{
			//Check for end of document
			int eventType = _xml.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {
				//Search for record tags
				if ((eventType == XmlPullParser.START_TAG) &&(_xml.getName().equals("record"))){
					//Record tag found, now get values and insert record
					String _Title = _xml.getAttributeValue(null, AnimalColumns.TITLE);
					String _Color = _xml.getAttributeValue(null, AnimalColumns.COLOR, 0);
					_Values.put(AnimalColumns.TITLE, _Title);
					_Values.put(AnimalColumns.COLOR, _Color);
					db.insert(AnimalColumns.TABLENAME, null, _Values);        		
				}
				eventType = _xml.next();
			}
		}
		//Catch errors
		catch (XmlPullParserException e)
		{		
			Log.e(TAG, e.getMessage(), e);
		}
		catch (IOException e)
		{
			Log.e(TAG, e.getMessage(), e);
			
		}        	
		finally
		{        	
			//Close the xml file
			_xml.close();
		}
	}

	/* Update database to latest version */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		//Crude update, make sure to implement a correct one when needed.
					
		Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
				+ newVersion + ", which will destroy all old data");
		db.execSQL("DROP TABLE IF EXISTS animals");
		onCreate(db);
	}
}

Let’s look at some of the code.

Here we get the xml file and open it

//Get xml resource file
Resources res = fContext.getResources();

//Open xml file
XmlResourceParser _xml = res.getXml(R.xml.animals_records);

Next we loop trough the xml file and check for record tags

//Check for end of document
int eventType = _xml.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
	//Search for record tags
	if ((eventType == XmlPullParser.START_TAG) &&(_xml.getName().equals("record"))){

Last we get the values from the attributes and insert a record into our table.

//Record tag found, now get values and insert record
String _Title = _xml.getAttributeValue(null, AnimalColumns.TITLE);
String _Color = _xml.getAttributeValue(null, AnimalColumns.COLOR, 0);
_Values.put(AnimalColumns.TITLE, _Title);
_Values.put(AnimalColumns.COLOR, _Color);
db.insert(AnimalColumns.TABLENAME, null, _Values);  

Happy coding

This was the first code example of 2012, I hope it will be of some use to my readers.
Till next time, happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *