您可以使用:
if(text != null) {
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("BROADCAST").setMessage(text).create();
alertDialog.getWindow().setType(
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
}
或檢查空字符串:
if(!text.equals("") {
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("BROADCAST").setMessage(text).create();
alertDialog.getWindow().setType(
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
}
或兩項:
if(text != null && !text.equals("") {
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("BROADCAST").setMessage(text).create();
alertDialog.getWindow().setType(
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
}
編輯:如果您嘗試檢查字符串是否等於l到單詞「null」,那麼你原來的代碼看起來很好。我會建議使用調試器或打印一些日誌語句來檢查發生了什麼。
所以:
private static final String TAG = "SomeActivity";
if (!text.equals("null")) {
// Not equal to the word null
Log.d(TAG, "text value should NOT be null and is: " + text);
//AlertDialog alertDialog = new AlertDialog.Builder(this)
// .setTitle("BROADCAST").setMessage(text).create();
// alertDialog.getWindow().setType(
// WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
// alertDialog.show();
} else {
// don't show
Log.d(TAG, "text value should be null and is: " + text);
}
但實際上這只是測試你已經不是犯了一個錯誤。對此,我建議不要使用「null」來表示空字符串。這可能會讓其他人看到代碼時感到困惑。堅持更「標準化」的「」。
http://stackoverflow.com/questions/2601978/how-to-check-if-my-string-is - 等於零 – WOUNDEDStevenJones
可能重複[如何檢查我的字符串是否等於空?](http://stackoverflow.com/questions/2601978/how-to-check-if-my-string-is-等於零) –
您的if語句正在檢查文本是否等於字符串「null」。如果你想檢查String對象是否爲null或不爲空,請看@MichaelVescovo的第一個例子。 – Arcaeic