I got an XML-file with the data I want to store in the SQLite database I made in my project in Android Studio. The data need to be in the SQLite database before the users can use the application. I've googled and tried many solutions but can't get it to work. Can someone help me?
Down below is my method for create the tables in the database and my try to fill one table with data from my XML-file. The file is named ingredients.xml and is in a map named xml under res. The fields INGREDIENT_TABLE (the name of the table) and Ingredient_Col_2 (the column were the ingredient are going to be stored) are declared above this method.
ingredients.xml
<?xml version="1.0" encoding="utf-8"?>
<ingredients>
<ingredient title="Amaranth" />
<ingredient title="Bovete" />
<ingredient title="Durra" />
<ingredient title="Fibrex" />
<ingredient title="Havre" />
<ingredient title="Hirs" />
<ingredient title="Kokos" />
<ingredient title="Linfrön" />
<ingredient title="Mandel" />
<ingredient title="Mandelmjöl" />
<ingredient title="Majsmjöl" />
<ingredient title="Mjölmix" />
<ingredient title="Finmjölmix" />
<ingredient title="Grovmjölmix" />
</ingredients>
@Override
public void onCreate(SQLiteDatabase db) {
// Execute the queries above.
db.execSQL(CREATE_TABLE_RECIPE);
db.execSQL(CREATE_TABLE_CATEGORY);
db.execSQL(CREATE_TABLE_INGREDIENT);
db.execSQL(CREATE_TABLE_MEASURE);
db.execSQL(CREATE_TABLE_COOKING);
// Pre-fill the tables that need data from the start.
ContentValues ingredient = new ContentValues();
// Get xml from resource.
Resources res = fContext.getResources();
// Open xml file.
XmlResourceParser _xml = res.getXml(R.xml.ingredients);
if (_xml != null) {
try {
int eventType = _xml.getEventType();
// As long as the document is not in the end keep looping.
while (eventType != XmlPullParser.END_DOCUMENT) {
/*
If the start tag in the document and the tag ingredient is not matching
do the statement.
*/
if ((eventType != XmlPullParser.START_TAG) && (_xml.getName().equals("ingredient"))) {
String ingredientName = _xml.getAttributeValue(null, Ingredient_Col_2);
ingredient.put(Ingredient_Col_2, ingredientName);
// Insert into the database. Null makes a new auto key and value is the
// ingredient on row in the XML-document right now. ??
db.insert(INGREDIENT_TABLE, null, ingredient);
}
eventType = _xml.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//Close the xml file
_xml.close();
}
}
}
Aucun commentaire:
Enregistrer un commentaire