java - 从 EditText 更新数据库

标签 java android

我在 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/

相关文章:

android - Signature.hashCode 指的是正确的 hashCode 吗?

android - 致命的安卓 12 : Exception: startForegroundService() not allowed due to mAllowStartForeground false

java - 对同步映射的键集进行线程安全迭代

java - Spring 数据 mongodb : Text search for 'phrase OR words in phrase'

java - 使用express在 Node 服务器上接收JSON对象

android - 如何在 Android 应用程序中播放不同的视频文件?

android - 授权的SIP Stack注册包

java - Hibernate:防止角色表中有多个相同的条目

java - 在Java中,全局变量总是放在堆上吗?

java - Android:从mysql获取数据时doInBackground出错