从EditText更新数据库

时间:2010-09-22 15:01:31

标签: java android

我在SQLite数据库中有一个文本字段,我希望用户能够更新。

因此,我在EditText视图中提取并显示文本。用户编辑它并按“更新”按钮。此时,我想用EditText中的任何用户更新数据库中的文本字段。

问题在于,EditText返回可编辑类型 并且我在更新记录时使用的 put(String key,String value)函数ContentValues需要 String 。那么如何在字符串中放置可编辑?

我尝试向上转换Editable to CharSequence,然后将其转换为String,但这给了我一个运行时异常,ClassCastException,它应该很好(因为该对象是一个可编辑的开头,我不能使它成为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");
}

}

1 个答案:

答案 0 :(得分:2)

这应该这样做:

String.valueOf(editTextName.getText())
相关问题