我在 SQLite 数据库中有一个文本字段,我希望用户能够更新它。
所以我提取文本并将其显示在 EditText View 中。用户对其进行编辑并按下“更新”按钮。此时我想用用户在 EditText 中拥有的任何内容更新数据库中的文本字段。
问题来了,EditText返回类型Editable。
我在更新记录时使用的 ContentValues 的 put(String key, String value) 函数需要一个 String。那么如何将 Editable 放入字符串中呢?
我尝试将 Editable 向上转换为 CharSequence,然后将其转换为 String,但这给了我一个运行时异常,ClassCastException,它应该这样做(因为对象一开始就是一个 Editable,我不能将它变成一个 String) .
那么如何解决这个问题呢?这是我正在使用的代码。我知道这是错误的,但我不知道该怎么做。
@Override
public void onClick(View v) {
// update logic
CharSequence strNewName = editTextName.getText();
//Update record in the table
ContentValues newRecord = new ContentValues();
newRecord.put(GIDatabase.Students.NAME, (String strNewName); //ClassCastException here
int rowsEffected = db.update(GIDatabase.Students.STUDENTS_TABLE_NAME, newRecord, GIDatabase.Students._ID + "=?", new String[]{strId});
if (rowsEffected != 1) {
// This should never be reached
throw new RuntimeException("Error updating name");
}
最佳答案
应该这样做:
String.valueOf(editTextName.getText())
关于java - 从 EditText 更新数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3770576/