0

私は現在Androidを貸し出しており、仕事を支援するアプリを書いています。私はこの優れたWebサイトをかなり前から使用しており、一般的に多くの調査を行った後、ほとんどの概念に頭を悩ませることができました。

簡単な答えがあると確信しているので、最初の質問をするつもりでした。次のステートメントのロジックは期待どおりに機能していません。

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を出力するだけなので機能しません。

劣等生でごめんなさい!

どうもありがとう、

デビッド

4

1 に答える 1

3

Androidには、空()との両方をチェックするための優れたユーティリティメソッドがあります""null Strings

TextUtils.isEmpty(str)

それはただです(str == null || str.length() == 0)が、それはあなたに少しのコードを節約します。

" "空白( )のみを含む文字列を除外する場合は、trim()

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

str.length() == 0Java 1.6を使用して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 + ")";
于 2012-08-17T12:30:38.303 に答える