Android How to create database on Startup if it doesn't exist and then retrieve it on next Startups

江枫思渺然 提交于 2019-12-24 14:49:18

问题


I am having trouble using SQLite on Android. I am able to parse a XML file and then create a database to store the content. Creation, insertion works fine. I can see the .db File in the File Explorer

My last call to checkDataBase() returns false ?! Why ?

I am working on Android 2.3 on en emulator.

Am I doing something wrong ?

Activity:

public class MTGDBActivity extends Activity{

    String currentDBPath = "data/data/rudy.jaumain.mtgdb/databases/MTGCards";
    MTGContainerData mtgcd;
    MTGDatabase mtgdb;

    Button buttonEditions, buttonCollection, buttonDecks;
    View v;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
                this.mtgcd = new MTGContainerData(this);
                if (!this.checkDataBase()) {
                    System.out.println("FILE DOESN'T EXIST");
                    this.mtgdb = new MTGDatabase(this);
                    this.mtgdb.open();
                    this.mtgcd.loadCards(this.mtgdb);
                    System.out.println("CARDS LOADED");
                    this.mtgdb.close();
                }
                else{
                    System.out.println("FILE DOES EXIST");
                }

        } catch (Exception e) {
            System.out.println("FAIL");
        }

        System.out.println(this.checkDataBase());
        this.setContentView(R.layout.main);
        this.initialize();
    }

    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            checkDB = SQLiteDatabase.openDatabase(currentDBPath, null,
                    SQLiteDatabase.OPEN_READONLY);
            checkDB.close();
        } catch (SQLiteException e) {
            System.out.println("DATABASE DOES NOT EXIST");
        }
        return checkDB != null ? true : false;
    }


    public void initialize(){
        try{

            v = (View)this.findViewById(R.id.mainLayout);
            v.setBackgroundColor(Color.WHITE);

            this.buttonEditions = (Button)findViewById(R.id.buttonEdition);
            this.buttonEditions.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v) {

                    System.out.println("CLICKED");
                        Intent i = new Intent(v.getContext(), MTGDBEditionsActivity.class);
                        startActivityForResult(i,0);
                }
            });

            this.buttonCollection = (Button)findViewById(R.id.buttonCollection);
            this.buttonCollection.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v) {

                    System.out.println("CLICKED");
                        Intent i = new Intent(v.getContext(), MTGDBCollectionActivity.class);
                        startActivityForResult(i,0);
                }
            });

            this.buttonDecks = (Button)findViewById(R.id.buttonDecks);
            this.buttonDecks.setOnClickListener(new OnClickListener(){
                @Override
                public void onClick(View v) {

                    System.out.println("CLICKED");
                        Intent i = new Intent(v.getContext(), MTGDBDecksActivity.class);
                        startActivityForResult(i,0);
                }
            });

        }
        catch(Exception e1){
            e1.printStackTrace();
        }

    }
}

Database:

public class MTGDatabase{

private static final String TABLE_CARDS = "table_cards";
private static final String COL_ID = "ID";
private static final int NUM_COL_ID = 0;
private static final String COL_NAME = "NAME";
private static final int NUM_COL_NAME = 1;
private static final String COL_EDITION = "EDITION";
private static final int NUM_COL_EDITION = 2;
private static final String COL_RARITY = "RARITY";
private static final int NUM_COL_RARITY = 3;
private static final String COL_MANACOST = "MANACOST";
private static final int NUM_COL_MANACOST = 4;
private static final String COL_NUMBER = "NUMBER";
private static final int NUM_COL_NUMBER = 5;
private static final String COL_COLOR = "COLOR";
private static final int NUM_COL_COLOR = 6;

public int VERSION_BDD = 1;
private SQLiteDatabase sqldb;
private MTGDatabaseAdapter mtgbdAdapter;

public MTGDatabase(Context c) {
    mtgbdAdapter = new MTGDatabaseAdapter(c, "MTGCards.db", null, VERSION_BDD);
}

public void open(){
    sqldb = mtgbdAdapter.getWritableDatabase();
}

public void close(){
    sqldb.close();
}

public SQLiteDatabase getDatabase(){
    return sqldb;
}

public long insertCard(MTGCard card){
    ContentValues values = new ContentValues();
    values.put(COL_NAME, card.getName());
    values.put(COL_EDITION, card.getEdition());
    values.put(COL_RARITY, card.getRarity());
    values.put(COL_MANACOST, card.getManacost());
    values.put(COL_NUMBER, card.getNumber());
    values.put(COL_COLOR, card.getColor());
    return sqldb.insert(TABLE_CARDS, null, values);
}

public int updateCard(int id, MTGCard card){
    ContentValues values = new ContentValues();
    values.put(COL_NAME, card.getName());
    values.put(COL_EDITION, card.getEdition());
    values.put(COL_RARITY, card.getRarity());
    values.put(COL_MANACOST, card.getManacost());
    values.put(COL_NUMBER, card.getNumber());
    values.put(COL_COLOR, card.getColor());
    return sqldb.update(TABLE_CARDS, values, COL_ID + " = " +id, null);
}

public int removeCardWithID(int id){
    return sqldb.delete(TABLE_CARDS, COL_ID + " = " +id, null);
}

public MTGCard getCardWithName(String name){
    Cursor c = sqldb.query(TABLE_CARDS, new String[] {COL_ID, COL_NAME, COL_EDITION, COL_RARITY, COL_MANACOST, COL_NUMBER, COL_COLOR}, COL_NAME + " LIKE \"" + name +"\"", null, null, null, null);
    return cursorToCard(c);
}


private MTGCard cursorToCard(Cursor c){

    if (c.getCount() == 0)
        return null;

    c.moveToFirst();

    MTGCard card = new MTGCard();
    card.setId(c.getInt(NUM_COL_ID));
    card.setName(c.getString(NUM_COL_NAME));
    card.setEdition(c.getString(NUM_COL_EDITION));
    card.setRarity(c.getString(NUM_COL_RARITY));
    card.setManacost(c.getString(NUM_COL_MANACOST));
    card.setNumber(c.getString(NUM_COL_NUMBER));
    card.setColor(c.getString(NUM_COL_COLOR));

    c.close();

    return card;
}
}

Database Adapter:

public class MTGDatabaseAdapter extends SQLiteOpenHelper {
private static final String TABLE_CARDS = "table_cards";
private static final String COL_ID = "_ID";
private static final String COL_NAME = "NAME";
private static final String COL_EDITION = "EDITION";
private static final String COL_RARITY = "RARITY";
private static final String COL_MANACOST = "MANACOST";
private static final String COL_NUMBER = "NUMBER";
private static final String COL_COLOR = "COLOR";

private static final String CREATE_BDD = "CREATE TABLE " 
    + TABLE_CARDS 
+ " (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " 
+ COL_NAME + " TEXT NOT NULL, "
+ COL_EDITION + " TEXT NOT NULL, "
+ COL_RARITY + " TEXT NOT NULL, "
+ COL_MANACOST + " TEXT NOT NULL, "
+ COL_NUMBER + " TEXT NOT NULL, "
+ COL_COLOR + " TEXT NOT NULL);";

public MTGDatabaseAdapter(Context context, String name,
        CursorFactory factory, int version) {
    super(context, name, factory, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(CREATE_BDD);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE " + TABLE_CARDS + ";");
    onCreate(db);
}
}

回答1:


I would advise you to use the SQLiteOpenHelper class: http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html

This class will create the database if it does not exist, for this it will execute code in the onCreate() method, which you can override if you extend the SQLiteOpenHelper class.

You can retrieve a database instance by calling the getReadableDatabase() and getWritableDatabase() methods.




回答2:


Calling getReadableDatabase() or getWriteableDatabase() on your SQLiteOpenHelper instance will create the database if it has not been already. You should not need any hardcoded paths in your implementation in order to set up your application's database (I'm not sure what you are trying to do with "parsing the XML").

See the NotePad tutorial on the developers site for a reference when creating your SQLiteOpenHelper class.

See this post for some information on how to correctly handle your SQLiteOpenHelper over the course of the application's lifecycle.




回答3:


Your database names are different (extension wise).

Change:

String currentDBPath = "data/data/rudy.jaumain.mtgdb/databases/MTGCards";

To this:

String currentDBPath = "data/data/rudy.jaumain.mtgdb/databases/MTGCards.db";

*Note that you are missing .db in your database's file name



来源:https://stackoverflow.com/questions/10199283/android-how-to-create-database-on-startup-if-it-doesnt-exist-and-then-retrieve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!