I am trying to call updateDatabase() method in my content provider from inside my SQLiteOpenHelper class so I will only upgrade the database when version changes and not every time the app compiles. I am not fluent enough in Android to know what to do, can someone help me?
Basically I have an update method outside of SQLiteOpenHelper and I need onUpgrade() to access outside method updateDataBase().
Below is a simplified code of what I actually have and is all I need to illustrate the problem( might have extra curly braces):
public class PeriodicTable extends ContentProvider {
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db){
db.execSQL(CREATE_DB_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + ELEMENTS_TABLE_NAME);
//I want to call updateDatabase() here
//so I can update database not every time I compile
onCreate(db);
}
}
public void updateDatabase(){
Context context = getContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
db = dbHelper.getWritableDatabase();
if(db != null){
try {
XmlPullParserHandler parser = new XmlPullParserHandler();
InputStream is = context.getAssets().open("elements.xml");
elements = parser.parse(is);
} catch (IOException e) {e.printStackTrace();}
try{
ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
//ContentValues[] values = new ContentValues[elements.size()];
db.beginTransaction();
for(int i=0; i<elements.size(); i++){
ContentValues v = new ContentValues();
Element current = elements.get(i);
v.put(ATOMIC_NUMBER, current.getAtomicNumber());
v.put(SYMBOL, current.getSymbol());
v.put(NAME, current.getName());
v.put(MOLAR_MASS, current.getMolarMass());
//System.out.println("@@@@@@@@@@@@@" + v.get(NAME));
operations.add(ContentProviderOperation.newInsert(CONTENT_URI).withValues(v).build());
}
db.setTransactionSuccessful();
applyBatch(operations);
}catch (final OperationApplicationException e1){
}
finally {
db.endTransaction();
}
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire