【问题标题】:Android logic issueAndroid逻辑问题
【发布时间】:2012-08-17 11:51:11
【问题描述】:

我目前正在学习 Android 并编写一个应用程序来帮助我完成工作。我使用这个优秀的网站已经有一段时间了,总的来说,经过大量研究,它帮助我理解了大多数概念。

我想我会问我的第一个问题,因为我确信它会有一个简单的答案 - 以下语句中的逻辑没有按预期工作:

protected void onListItemClick(ListView l, View v, final int pos, final long id){

    Cursor cursor = (Cursor) rmDbHelper.fetchInspection(id);
    String inspectionRef = cursor.getString(cursor.getColumnIndex(
            RMDbAdapter.INSPECTION_REF));
    String companyName = cursor.getString(cursor.getColumnIndex(
            RMDbAdapter.INSPECTION_COMPANY));

    if (inspectionRef == null && companyName == null){
        inspectionDialogueText = "(Inspection Reference unknown, Company Name unknown)";    
    }
    else if (inspectionRef != null && companyName == null) {
        inspectionDialogueText = "(" + inspectionRef + ", Company Name unknown)";
        }
    else if (inspectionRef == null && companyName != null) {
        inspectionDialogueText = "(Inspection Reference unknown, " + companyName + ")";
    }
    else {
        inspectionDialogueText = "(" + inspectionRef + ", " + companyName + ")";
    }

我不确定是否应该在 if 语句中使用 null 或 "" 但无论哪种方式它都不起作用,因为它只打印inspectionRef 和 companyName 而不管它们是否包含任何内容..

对不起,如果我只是个笨蛋!

非常感谢,

大卫

【问题讨论】:

  • 您还应该在 == null 检查后检查 isEmpty

标签: android null logic


【解决方案1】:

Android 有一个很好的 utility method 来检查空 ("") 和 null Strings

TextUtils.isEmpty(str)

这只是(str == null || str.length() == 0),但它可以为您节省一些代码。

如果您想过滤掉仅包含空格 (" ") 的字符串,您可以添加 trim()

if (str == null || str.trim().length() == 0) { /* it's empty! */ }

如果您使用的是 Java 1.6,则可以将 str.length() == 0 替换为 str.isEmpty()

例如,您的代码可以替换为

if (TextUtils.isEmpty(inspectionRef)){
    inspectionRef = "Inspection Reference unknown";
}
if (TextUtils.isEmpty(companyName)){
    companyName = "Company Name unknown";
}
// here both strings have either a real value or the "does not exist"-text
String inspectionDialogueText = "(" + inspectionRef + ", " + companyName + ")";

如果你在你的代码中使用那段逻辑,你可以把它放在一些实用方法中

/** returns maybeEmpty if not empty, fallback otherwise */
private static String notEmpty(String maybeEmpty, String fallback) {
    return TextUtils.isEmpty(maybeEmpty) ? fallback : maybeEmpty;
}

并像使用它一样

String inspectionRef = notEmpty(cursor.getString(cursor.getColumnIndex(
        RMDbAdapter.INSPECTION_REF)), "Inspection Reference unknown");
String companyName = notEmpty(cursor.getString(cursor.getColumnIndex(
        RMDbAdapter.INSPECTION_COMPANY)), "Company Name unknown");

inspectionDialogueText = "(" + inspectionRef + ", " + companyName + ")";

【讨论】:

  • 您好 Zapl,感谢您的详细回复。今晚我会试试这个。会在您的回答者中添加一个勾号,但我还没有代表!干杯,戴夫。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
  • 2015-07-19
相关资源
最近更新 更多