【问题标题】:Database update crashing app数据库更新崩溃的应用程序
【发布时间】:2012-09-27 01:35:39
【问题描述】:

代码:

    final String nome = nm.getText().toString();
            final String telefone = tlf.getText().toString();
            if(nome.length() != 0 && telefone.length() != 0){
                if(mIndex.equals("")) {                 
                    ContentValues valor = new ContentValues();
                    valor.put("nome", nome);
                    valor.put("telefone", telefone);
                    db.insert("contatos", null, valor);
                    ShowMessage("Sucesso","O Contato " + nome + " foi salvo com sucesso");
                }
                else {
                    String[] whereArgs = {"nome", "telefone"};

                    ContentValues dataToInsert = new ContentValues();                          
                    dataToInsert.put("nome", nome);
                    dataToInsert.put("telefone", telefone);

                    db.update("contatos", dataToInsert, "nome='"+nomeant+"' and telefone='"+foneant+"' ", whereArgs);
                    ShowMessage("Sucesso","O Contato " + nome + " foi editado com sucesso");
                }
            }

因此,mIndex 是上一个活动中联系人的索引(我选择并单击项目/联系人,然后将索引传递给新活动)因此,如果 EditTexts 已经为空白,它将添加一个新联系人,如果 EditTexts 有一个值并被更改,它将改变 Clicked Contacts 值(姓名/电话)。但是当我点击 SAVE 按钮时,我的应用程序崩溃了,但错误出现在 db.update 行中。

db.update("contatos", dataToInsert, "nome='"+nomeant+"' and telefone='"+foneant+"' ", whereArgs); 所以我猜 whereClause 或 whereArgs 是错误的,但因为我在 Android 编程方面没有很高的智能。

【问题讨论】:

  • 这里,我的另一个问题的 [LINK[(stackoverflow.com/questions/12589582/…),它有 LogCat 错误和我的 main.Java 的代码,现在我没有打开“VerificaDados();”在我的 onCreate 中,所以数据库没有显示错误。
  • 试试 Mukesh Soni 建议的答案

标签: android database


【解决方案1】:

这里不需要 whereArgs,因为您在 where 子句本身中附加了参数。只需提供 null 来代替 whereArgs -

 db.update("contatos", dataToInsert, "nome='"+nomeant+"' and telefone='"+foneant+"'", null);

但使用参数总是更好。它可以防止 sql 注入并且还负责转义特殊字符。在你的情况下 -

db.update("contatos", dataToInsert, "nome=? and telefone=?", whereArgs);

另外,你的 whereArgs 是错误的。应该是——

String[] whereArgs = new String[] {nomeant, foneant};

【讨论】:

  • 好的,它起作用了:db.update("contatos", dataToInsert, "nome='"+nomeant+"' and telefone='"+foneant+"'", null); 感谢您的帮助。顺便说一句,db.update("contatos", dataToInsert, "nome=? and telefone=?", whereArgs); 没有显示错误,但它没有正确保存值。
  • 会的。你 whereArgs 是错误的。应该是这样 - String[] whereArgs = new String[] {nomeant, foneant};
  • 是的,我只是在等待时机。
猜你喜欢
  • 1970-01-01
  • 2014-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
  • 2013-02-04
相关资源
最近更新 更多