获取SQLite单个单元格并在单个TextView

时间:2015-10-20 19:56:49

标签: 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 Parent):

DBAdapter myDb = new DBAdapter(this);

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

虽然这会产生无错误的环境,但由于我尚未解决的"No such table"错误(code 1)导致应用崩溃。

END ANSWER

首先,我知道有很多这类问题。我至少看了十几个,似乎无法绕过它,所以我发布了一个问题,希望有人可以帮我一个忙,并向我解释一下细节以及提供方法。

我想创建一个方法来获取我指定的KEY_NAME的{​​{1}}。 (我认为这可以使用KEY_ROWID中已经存在的getRow()方法来完成。然后,将其转换为字符串,以便将其显示为DBAdapter

我需要知道如何填写名为TextView

DBAdapter底部的方法

一个完美的答案将允许我在一个单独的活动中编写以下代码,设置标题:getName

非常感谢您的时间。

我有一个非常好的mTitle1 = getName;由我遵循的教程提供:

DBAdapter

以下是PPartisan的建议:

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) {

}

}

Zahan的建议:

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;

2 个答案:

答案 0 :(得分:1)

创建方法getName,如下所示

public String getName(long l)
{
    String[] columns=new String[]{KEY_NAME,KEY_ROWID};
    Cursor c=yourDatabase.query(DATABASE_TABLE_NAME,columns,KEY_ROWID + "=" + l,null,null,null,null);
   if(c!=null)
   {
   c.moveToFirst();
   String name=c.getString(1);   // use your desired column's index instead of 1
   return name;
   }
return null;
}

现在您可以从您的活动中调用并设置TextView likelike

Your_db_class object_name=new Your_db_class();
object_name.open();    
String mTitle1 = object_name.getName(1);  //KEY_ROWID
object_name.close();
textView.setText(""+mTitle1+"");

答案 1 :(得分:1)

从Android中的SQLite数据库中检索数据涉及使用query()方法运行查询,理想情况下(IMO)(您也可以使用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