Я пытаюсь настроить базу данных с помощью Contentproviders и попал в ловушку.Когда я использовал отладчик для пошагового выполнения кода, он показывает, что код сначала запускается из класса ContentProvider, а не из основного класса!Как это вообще возможно ?Может кто-нибудь мне помочь ?Заранее спасибо !
Первый код - это основной код, а второй - класс провайдера
public class MedF1 extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drug_list);
ListView drugListView;
ArrayAdapter<Drug> aa;
ArrayList<Drug> drugs = new ArrayList<Drug>();
drugListView = (ListView)this.findViewById(R.id.list1);
DrugProvider.DatabaseHelper mDbHelper1 = new DrugProvider.DatabaseHelper(this);
//Creation of the Database here
try {
mDbHelper1.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
mDbHelper1.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
//Database created now to fill the view
int layoutID = android.R.layout.simple_list_item_1;
aa = new ArrayAdapter<Drug>(this, layoutID , drugs);
drugListView.setAdapter(aa);
//
loadDrugsFromProvider();
}
Это ContentProvider.Отладчик показывает первый шаг, к которому осуществляется доступ, это конструктор DatabaseHelper!Это нормально ?Разве метод onCreate основного класса не должен всегда стоять на первом месте?
public class DrugProvider extends ContentProvider {
//Variable declaration omitted for brevity.
private static SQLiteDatabase myDataBase;
// Creation of the database and its basic parameters
public static class DatabaseHelper extends SQLiteOpenHelper {
public final Context myContext;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just
* created empty database in the system folder, from where it can be
* accessed and handled. This is done by transferring byte stream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}