2012-08-17 146 views
0

我目前正在学习Android并编写一个应用程序来帮助我完成工作。我一直在使用这个优秀的网站已经有一段时间了,经过大量的研究后,它帮助我理解了大多数概念。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,无论它们是否包含任何东西。

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

非常感谢,

大卫

+1

你也应该检查的isEmpty == NULL检查 – nandeesh 2012-08-17 11:52:38

回答

3

Android有一个很好的utility method检查都是空的("")和nullStrings

TextUtils.isEmpty(str) 

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

如果您想筛选出只包含空白(" ")字符串,你可以添加一个trim()

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

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

你的代码可以用于示例被替换为

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 + ")"; 
+0

后嗨Zapl,谢谢你的详细回复。今晚我会和你一起去的。会给你的anwser添加一个勾号,但我还没有代表!干杯,戴夫。 – Scamparelli 2012-08-20 10:39:54