android - 获取 SQLite 单个单元格并在单个 TextView 中显示

标签 android sqlite

回答:请注意,我结合了这两种建议来生成以下代码:

DBAdapter.java:

String name = "";

public String getName(long l) {
    Cursor result = myDBHelper.getReadableDatabase().query(
            DBAdapter.DATABASE_TABLE_NAME, //Name of your table
            new String[] { DBAdapter.KEY_NAME }, //List of columns to return, as a String array. Just one in your case.
            DBAdapter.KEY_ROWID + "=?", //The row selection criteria. Equivalent to saying "Where the key id is equal to..."
            new String[] { String.valueOf(l) }, //...this value
            null, //This parameter deals with grouping results. No need here, hence null.
            null, //Relates to the above. Also null.
            null //Orders results. There should just be one, so it's null here, but can be useful.
    );

    if (result.moveToFirst()) {
        name = result.getString(result.getColumnIndex(DBAdapter.KEY_NAME));
    }
    return name;

CharacterInfo.java(NavigationDrawer 父级):

DBAdapter myDb = new DBAdapter(this);

myDb.open();
String name = myDb.getName(1);
mTitle1 = name;
myDb.close();

虽然这产生了一个无错误的环境,但应用程序因 “No such table” 错误 (code 1) 而崩溃,我尚未解决。

结束答案

首先,我知道有很多此类问题。我已经看了至少一打,但似乎无法理解它,所以我发布了一个问题,希望有人能帮我一个忙,并在提供方法的同时更详细地向我解释.

我想创建一个方法来获取我指定的 KEY_ROWIDKEY_NAME。 (我认为这可以使用 DBAdapter 中已有的 getRow() 方法来完成)。然后,将其转换为字符串以将其显示为 TextView

我需要知道如何填写 DBAdapter 底部名为 getName 的方法

一个完美的答案将允许我在设置标题的单独 Activity 中编写以下代码:mTitle1 = getName;

非常感谢大家的宝贵时间。

我有一个非常好的 DBAdapter,由我遵循的教程提供:

public class DBAdapter {

private static final String TAG = "DBAdapter"; //used for logging database version changes

// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_DATE = "date";

public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_DATE};

// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_NAME = 1;
public static final int COL_DATE = 2;

// DataBase info:
public static final String DATABASE_NAME = "dbCharacters";
public static final String DATABASE_TABLE = "Character_Info";
// The version number must be incremented each time a change to DB structure occurs.
public static final int DATABASE_VERSION = 2;

//SQL statement to create database
private static final String DATABASE_CREATE_SQL = 
        "CREATE TABLE " + DATABASE_TABLE 
        + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + KEY_NAME + " TEXT NOT NULL, "
        + KEY_DATE + " TEXT"
        + ");";

private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;


public DBAdapter(Context ctx) {
    this.context = ctx;
    myDBHelper = new DatabaseHelper(context);
}

// Open the database connection.
public DBAdapter open() {
    db = myDBHelper.getWritableDatabase();
    return this;
}

// Close the database connection.
public void close() {
    myDBHelper.close();
}

// Add a new set of values to be inserted into the database.
public long insertRow(String name, String date) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_NAME, name);
    initialValues.put(KEY_DATE, date);

    // Insert the data into the database.
    return db.insert(DATABASE_TABLE, null, initialValues);
}

// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    return db.delete(DATABASE_TABLE, where, null) != 0;
}

public void deleteAll() {
    Cursor c = getAllRows();
    long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
    if (c.moveToFirst()) {
        do {
            deleteRow(c.getLong((int) rowId));              
        } while (c.moveToNext());
    }
    c.close();
}

// Return all data in the database.
public Cursor getAllRows() {
    String where = null;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, 
                    where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String date) {
    String where = KEY_ROWID + "=" + rowId;
    ContentValues newValues = new ContentValues();
    newValues.put(KEY_NAME, name);
    newValues.put(KEY_DATE, date);
    // Insert it into the database.
    return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}


private static class DatabaseHelper extends SQLiteOpenHelper
{
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase _db) {
        _db.execSQL(DATABASE_CREATE_SQL);           
    }

    @Override
    public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading application's database from version " + oldVersion
                + " to " + newVersion + ", which will destroy all old data!");

        // Destroy old database:
        _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

        // Recreate new database:
        onCreate(_db);
    }
}

public void getName (long id) {

}

}

这是 PPartisan 的建议:

public String getName(long l) {
    Cursor result = myDBHelper.getReadableDatabase().query(
            DBAdapter.DATABASE_NAME, //Name of your database
            new String[] { DBAdapter.KEY_NAME }, //List of columns to return, as a String array. Just one in your case.
            DBAdapter.KEY_ROWID + "=?", //The row selection criteria. Equivalent to saying "Where the key id is equal to..."
            new String[] { String.valueOf(1) }, //...this value
            null, //This parameter deals with grouping results. No need here, hence null.
            null, //Relates to the above. Also null.
            null //Orders results. There should just be one, so it's null here, but can be useful.
    );

    if (result.moveToFirst()) {
        name = result.getString(result.getColumnIndex(DBAdapter.KEY_NAME));
    }
    return name;

扎汉的建议:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.character_info);

    mCharacterInfoDrawerFragment = (CharacterInfo_Drawer_Fragment)
            getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);

    openDB();
    String name = DBAdapter.getName(1);
    mTitle1 = name;
    closeDB();


    mCharacterInfoDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));



}

最佳答案

从 Android 中的 SQLite 数据库检索数据涉及运行查询,理想情况下 (IMO) 使用 query()方法(您也可以使用 rawQuery())。

由于数据库操作很容易运行很长时间(几秒),因此您希望查询数据库的次数尽可能少,使查询本身尽可能具体,并真正脱离 UI 线程执行。

例如,如果您确实只想访问数据库的一个“单元格”,那么您将构造一个 query(),如下所示:

Cursor result = myDbInstance.getReadableDatabase().query(
    DBAdapter.DATABASE_TABLE, //Name of your table
    new String[] { DBAdapter.KEY_NAME }, //List of columns to return, as a String array. Just one in your case.
    DBAdapter.KEY_ID + "=?", //The row selection criteria. Equivalent to saying "Where the key id is equal to..."
    new String[] { String.valueOf(idOfTheRowToQuery) }, //...this value
    null, //This parameter deals with grouping results. No need here, hence null.
    null, //Relates to the above. Also null.
    null //Orders results. There should just be one, so it's null here, but can be useful.
    )

所有这些都将返回一个 Cursor 对象。要访问存储的 String,您需要检查它是否有条目(它应该有),移动到第一个(在本例中也是唯一的)条目,然后运行以下命令:

if (result.moveToFirst()) {
    String name = result.getString(result.getColumnIndex(DBAdapter.KEY_NAME));
}

然后您只需将它分配给您的 TextView

不过要记住几点:

  1. 通常建议对数据库实例使用static synchronized singleton。看here了解更多信息。
  2. 如果您确实只需要一个条目,那么上面的就可以了。但是,如果您可能需要更多,那么出于性能原因,您应该以这样一种方式构建您的 query(),即它返回您需要的所有内容,并且尽可能少地传递。
  3. 数据库操作很慢,应该在 UI 线程之外执行。这通常是通过 AsyncTask 完成的,但无论如何它都不是唯一的方法。我写了一篇博客文章,其中涵盖了很多这些要点 here如果你有兴趣。

关于android - 获取 SQLite 单个单元格并在单个 TextView 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33245713/

相关文章:

安卓工作室 : build project error - Failed to complete Gradle execution

屏幕旋转后Android listview消失

javascript - jQuery 写入数据库 数据库

sqlite - 如何从损坏的 SQLite3 数据库中恢复数据?

javascript - 如何在 API 17 下的构建中忽略 @JavascriptInterface 注释 -Android

android - 如何检测是否需要 PIN/密码/图案来解锁手机?

android - 在sqlite android中创建用户定义的函数?

c++ - 在 QSqlQuery::addBindValue() 中为 LIKE 转义 %(百分比)

java - Android Junit - "Class not found"

android - 如何在 android 中应用 SELECT date ('now' ) 查询?