gpt4 book ai didi

android - 我如何为 Android 应用程序硬编码 SQLite 数据库

转载 作者:行者123 更新时间:2023-11-30 04:09:38 26 4
gpt4 key购买 nike

我正在开发一个需要使用数据库的 Android 应用程序。阅读了一段时间后,我决定使用 SQLite 数据库,我开始阅读我应该如何使用它,但是每本书/教程/等等……通过允许用户向其中添加信息来开发可更新的数据库。 (如日记或运行时间记录应用程序样式)。我只需要创建(我的意思是,就像硬编码一样)我的数据库并查询它。用户端无法更新我的数据库。我很确定这应该是一种简单/虚拟的方法,但我还没有找到它。所以,如果有人能帮助我,那就太棒了。 ;)

谢谢。阿梅特。

最佳答案

请检查以下链接: SQLite database tutorial with DAO and Content Provider .

你只需要 2 个类:

  • 数据库类(4.3. 数据库和数据模型):

公共(public)类 MySQLiteHelper 扩展 SQLiteOpenHelper {

public static final String TABLE_COMMENTS = "comments";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_COMMENT = "comment";

private static final String DATABASE_NAME = "commments.db";
private static final int DATABASE_VERSION = 1;

// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_COMMENTS + "(" + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_COMMENT
+ " text not null);";

// Database creation sql statement
private static final String TABLE_CREATE = "CREATE TABLE tablename....."

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

@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
database.execSQL(TABLE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// You don't need this. If you don't change the DATABASE_VERSION value then this method will not be called.
}

公共(public)类 CommentsDataSource {

// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_COMMENT };

public CommentsDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}

public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}

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

public List<Comment> getAllComments() {
List<Comment> comments = new ArrayList<Comment>();

Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
allColumns, null, null, null, null, null);

cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Comment comment = cursorToComment(cursor);
comments.add(comment);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return comments;
}

private Comment cursorToComment(Cursor cursor) {
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setComment(cursor.getString(1));
return comment;
}

  • 但我建议您也查看内容提供程序示例(8.4。创建内容提供程序)。一点都不复杂。

关于android - 我如何为 Android 应用程序硬编码 SQLite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11040260/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com