0

アクティビティが開始されるインテントは、デバイスがグループの所有者であるか、単に参加しているピアであるかによって異なります。現時点では、instructIntentは初期化されていません。Eclipseが示唆するように私はそれをnullにすることになっていますか?または、これを処理するためのより専門的なJavaコードスタイルの方法はありますか?

Intent instructIntent;
if (info.groupFormed && info.isGroupOwner) {
    Log.d(WiFiDirectActivity.TAG, "DeviceDetailFragment_onCreateView: btn_ready pressed on host");
    instructIntent = new Intent(getActivity(), LeaderActivity.class);
} else if (info.groupFormed) {
    Log.d(WiFiDirectActivity.TAG, "DeviceDetailFragment_onCreateView: btn_ready pressed on client");
    instructIntent = new Intent(getActivity(), MusicianActivity.class);
}

instructIntent.putExtra(Intent.EXTRA_TEXT, "Play");
instructIntent.putExtra(MusicService.EXTRAS_GROUP_OWNER_ADDRESS, info.groupOwnerAddress.getHostAddress());
instructIntent.putExtra(MusicService.EXTRAS_GROUP_OWNER_PORT, 8080);
startActivity(instructIntent);
4

2 に答える 2

1

nullにすることは役に立ちません。本当の問題は、info.groupFormedがfalseの場合、instructIntentに有効な値がないことです。ただし、nullに初期化しても、有効ではありません。つまり、putExtraを呼び出すと例外がスローされます。より良い方法は次のことです。

if(info.groupFormed){
    if(info.isGroupOwner){
        instructIntent = new Intent(getActivity(), LeaderActivity.class);
    }
    else{
        instructIntent = new Intent(getActivity(), MusicianActivity.class);
    }
    //all of your putExtra and startIntent calls here
}

インテントのputおよびstart呼び出しに行くすべてのブランチが、新しいインテントを作成することに注意してください。このようにして、メンバー関数を呼び出そうとするnullまたは単位化された変数がなくなります。

于 2013-02-13T19:05:03.083 に答える
-1

Javaで宣言された変数は、使用する前に値を指定する必要があります。上記のコードでは、ifとelseの両方の条件が満たされない場合、instructIntent変数に値を割り当てない可能性があります。

したがって、次のようにinstructIntentをnullに初期化する必要があります。

Intent instructIntent = null;
于 2013-02-13T19:09:56.163 に答える