GetSupportActionBar (toolbar) throws a null pointer exception using Butterknife for the toolbar

I use Butterknife to enter a view for a toolbar. But the getSupportActionBar(toolbar) method throws an exception from the null pointer, and the application, unfortunately, is stopped. What can be done to solve this problem? I am using Android 4.2. So, is there a problem using Butterknife with Jellybean?

Mainactivity

  public class MainActivity extends AppCompatActivity { @BindView(R.id.tool_bar_demo) Toolbar toolbar; @BindDrawable(R.drawable.backspace) Drawable backspace_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); setSupportActionBar(toolbar); toolbar.setTitle("ABC"); } } 

activity_main

  <android.support.v7.widget.Toolbar android:layout_width="match_parent" android:layout_height="58dp" android:id="@+id/tool_bar_demo" android:background="?attr/colorPrimary" android:minHeight="?attr/actionBarSize" android:titleTextColor="@color/colorAccent" /> </RelativeLayout> 

gradle

  minSdkVersion 15 targetSdkVersion 23 apply plugin: 'com.neenbedankt.android-apt' compile 'com.android.support:design:23.4.0' compile 'com.jakewharton:butterknife:8.0.1' apt 'com.jakewharton:butterknife-compiler:8.0.1' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' 
+6
source share
2 answers

This seems to be a problem with Butterknife .

The main points are collected from this problem:

Butter Knife is just sugar on findViewById, and this is what cannot be found. As I said, make sure the layout is in main_activity or make sure you put the toolbar with this identifier in the main_activity layout.

another comment says: if I set an id for mine, include it like this:

 <include android:layout_width="match_parent" android:layout_height="wrap_content" layout="@layout/toolbar" android:id="@+id/include4" /> 

This does not work. But if I remove android:id="@+id/include4" , this will work. Starting with version 7.0.1, adding an identifier to include causes the view to not be found.

Link to the question: id oil knife problem

+1
source

This is not actually related to Butterknife or Jellybean . This is a common exception that happens when you use an ActionBar theme with a Toolbar . And he says that you cannot use ActionBar and Toolbar at the same time.

As I mention in the comment, you should change your style as follows:

 <style name="YOUR_STYLE" parent="Theme.AppCompat.Light.NoActionBar"> .... other attrs here <item name="windowActionBar">false</item> </style> 

See this related thread to solve your problem.

+1
source

All Articles