Android数据库文件访问

时间:2013-02-01 15:44:16

标签: android sqlite

我有我的sqlite数据库文件,nhl.db,我把它放在我项目的assets目录中。然后我从eclipse运行模拟器并加载程序,但是当我调用db时,我得到一个'没有这样的表'错误。我检查了data / data / myapp / databases /目录,并且有一个文件名为我的数据库,但打开检查它,它是一个空的数据库文件,显然是由SqLiteOpenHelper创建的,因为它无法找到我的数据库。

我的问题是我在哪里放置我的sqlite数据库文件,以便它被打开而不是创建?

public class DatabaseHandlerSimple extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "nhl";

// Contacts table name
private static final String TABLE_PLAYERS = "players";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TEAM = "team";
private static final String KEY_NUMBER = "number";
private static final String KEY_FNAME = "firstname";
private static final String KEY_LNAME = "lastname";
private static final String KEY_POSITION = "position";

public DatabaseHandlerSimple(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Getting All Contacts
public List<Player> getAllPlayers() {
    List<Player> playerList = new ArrayList<Player>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_PLAYERS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Player player = new Player();
            player.setID(Integer.parseInt(cursor.getString(0)));
            player.setTeam(Integer.parseInt(cursor.getString(1)));
            player.setNumber(Integer.parseInt(cursor.getString(2)));
            player.setFirstName(cursor.getString(3));
            player.setLastName(cursor.getString(4));
            player.setPosition(Integer.parseInt(cursor.getString(5)));
            // Adding contact to list
            playerList.add(player);
        } while (cursor.moveToNext());
    }

    // return contact list
    return playerList;
}

@Override
public void onCreate(SQLiteDatabase arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
    // TODO Auto-generated method stub

}

}

2 个答案:

答案 0 :(得分:1)

有一个关于来自Vogella的SQLite的非常好的教程,请尝试修复它。 对我来说,看起来你没有在这里创建数据库。

答案 1 :(得分:1)

看看这个:http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

您可以删除.db扩展名,只需在资源文件夹中将其命名为nhl。