【问题标题】:Android Studio - Return error msg when sql query search record does not existAndroid Studio - 当sql查询搜索记录不存在时返回错误消息
【发布时间】:2020-09-14 14:20:50
【问题描述】:

我创建了一个带有内置 sqlite 数据库的 android 应用程序,用户进行搜索并显示数据。一切都很好,但是当用户搜索的内容不存在时,我完全坚持弹出错误消息。

我不想返回任何内容,我希望弹出消息说“记录不存在!”

这可能很简单,但我尝试的每个 IF 语句都有错误,希望有任何指针。

我的查询代码:

   public String getProduct(String userInput){
    c=db.rawQuery("select productname from Inventory where productname ='"+userInput+"'", new String[]{});
    StringBuffer buffer = new StringBuffer();
    while(c.moveToNext()){
        String product = c.getString(0);
        buffer.append(""+product);
    }
    return buffer.toString();
}

感谢您的帮助。

【问题讨论】:

    标签: java android android-studio mobile-application


    【解决方案1】:

    在您的 while 循环之前,您可以检查查询是否返回任何数据,如果不返回空字符串

    if(!c.moveToFirst()) return ""

    当您使用getProduct 时,您可以检查它是否为空

    String dbResult = getProduct(userInput);
    if(dbResult.isEmpty) {
      // Display "Record does not exist!"
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-31
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-19
      • 1970-01-01
      • 2022-06-16
      相关资源
      最近更新 更多