2

onCreate()活動的方法,我有這樣的代碼ToolBargetSupportActionBar()NullPointerException異常

toolbar = (Toolbar) findViewById(R.id.tool_bar); 
setSupportActionBar(toolbar); 
getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

我的IDE溫暖我getSupportActionBar().setDisplayHomeAsUpEnabled(true);可能產生NullPointerException

我的問題是我應該忽略它,我該如何解決它呢?

+2

你知道什麼是NullPointerException嗎? – Tunaki

+0

您正在使用哪個工具欄,您是否使用支持工具欄? – Bhargav

+0

@VirajNalawade他正在詢問Android Studio的警告。這不是關於實際的錯誤。 – hata

回答

5

的IDE會警告你潛在的NullPointerException因爲有很多情況下,該應用可能會拋出一個。例如,您可以使用整個Application(或僅針對相關的activity)使用NoActionBar主題,但仍嘗試使用getActionBar()(或getSupportActionBar())檢索操作欄的引用。

只要忽略警告,但請記住上述註釋。

UPDATE:

可以通過爲空性明確檢查擺脫了警告:

toolbar = (Toolbar) findViewById(R.id.tool_bar); 
if (toolbar != null) { 
    // you can safely invoke methods on the Toolbar 
    setSupportActionBar(toolbar); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
} else { 
    // Toolbar is null, handle it 
} 
+1

謝謝! – Daniel

2

你可以檢查空的,但如果不崩潰它不應該是nessessary:

if(getSupportActionBar() != null) { 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
} 
2

那麼這兩個問題的答案都是正確的,但如果你只是想刪除警告

ActionBar actionBar = getSupportActionBar(); 

assert actionBar != null; 

actionBar.setDisplayHomeAsUpEnabled(true); 

assert actionBar!= null,表示ActionBar不爲null ,所以調用此變量的任何方法不會產生NullPointerException的警告。

我想如果你

assert getSupportActionBar() != null 

但我不能肯定它會成功。

0

上述由NullPointerException異常逃避給出所有的答案,並把這個在你的代碼之後: -

if(getSupportActionBar() != null) { 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
} 

只有解決異常問題後,那麼你也將不僅能獲得您的工具欄爲空。 我想說只是檢查你的活動xml你已經宣佈你的工具欄或沒有,我認爲這將重新解決你的問題。

<android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar1" 
      android:layout_width="match_parent" 
      android:layout_height="?attr/actionBarSize" 
      android:background="?attr/colorPrimary" 
      app:popupTheme="@style/AppTheme.PopupOverlay" /> 

只要把工具欄在你activiy XML。

相關問題