简体   繁体   English

Android如何在启动时创建数据库(如果该数据库不存在),然后在下一次启动时检索它

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

I am having trouble using SQLite on Android. 我在Android上使用SQLite遇到麻烦。 I am able to parse a XML file and then create a database to store the content. 我能够解析一个XML文件,然后创建一个数据库来存储内容。 Creation, insertion works fine. 创建,插入工作正常。 I can see the .db File in the File Explorer 我可以在文件资源管理器中看到.db文件

My last call to checkDataBase() returns false ?! 我对checkDataBase()的最后一次调用返回false?! Why ? 为什么呢

I am working on Android 2.3 on en emulator. 我正在使用模拟器上的Android 2.3。

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);
}
}

I would advise you to use the SQLiteOpenHelper class: http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html 我建议您使用SQLiteOpenHelper类: 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. 如果该类不存在,则该类将创建数据库,为此它将在onCreate()方法中执行代码,如果扩展SQLiteOpenHelper类,则可以重写该代码。

You can retrieve a database instance by calling the getReadableDatabase() and getWritableDatabase() methods. 您可以通过调用getReadableDatabase()getWritableDatabase()方法来检索数据库实例。

Calling getReadableDatabase() or getWriteableDatabase() on your SQLiteOpenHelper instance will create the database if it has not been already. 如果getReadableDatabase()调用数据库,则在SQLiteOpenHelper实例上调用getReadableDatabase()getWriteableDatabase()将创建数据库。 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"). 在实现中,您不需要任何硬编码的路径即可设置应用程序的数据库(我不确定您要使用“解析XML”做什么)。

See the NotePad tutorial on the developers site for a reference when creating your SQLiteOpenHelper class. 创建SQLiteOpenHelper类时,请参阅开发人员网站上的NotePad教程以获取参考。

See this post for some information on how to correctly handle your SQLiteOpenHelper over the course of the application's lifecycle. 有关在应用程序生命周期中如何正确处理SQLiteOpenHelper一些信息,请参见这篇文章

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 *请注意,数据库文件名中缺少.db

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM