2016-05-03 5 views
52

Я использую butterknife 8.0.1, но появляется nullpointerexception.ButterKnife 8.0.1 не работает

Эта линия находится на моем build.grade файле: compile 'com.jakewharton:butterknife:8.0.1'

это мой Main Class: (я написал включает в себя должным образом)

import butterknife.BindView; 
import butterknife.ButterKnife; 

public class MainActivity extends BaseActivity { 

    @BindView(R.id.MainScreenTextView) TextView mainText; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     ButterKnife.bind(this); 

     **mainText.setText("Butter knife is working fine");** 
    } 

и это MainActivity.xml:

<android.support.design.widget.AppBarLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:theme="@style/AppTheme.AppBarOverlay"> 

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

</android.support.design.widget.AppBarLayout> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:gravity="center_vertical" 
    android:orientation="vertical"> 

    <TextView 
     android:id="@+id/MainScreenTextView" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="This is the Main Screen" 
     android:textColor="#000000" 
     android:background="#666666" 
     android:padding="5dp" 
     android:textSize="20dp"/> 
</LinearLayout> 

<android.support.design.widget.FloatingActionButton 
    android:id="@+id/fab" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="bottom|end" 
    android:layout_margin="@dimen/fab_margin" 
    android:src="@android:drawable/ic_dialog_email" /> 

ответ

141

Per the readme, вам необходимо включить butterknife-compiler для того, чтобы генерируемый код будет производиться автоматически:

buildscript { 
    repositories { 
    mavenCentral() 
    } 
    dependencies { 
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' 
    } 
} 

apply plugin: 'com.neenbedankt.android-apt' 

dependencies { 
    compile 'com.jakewharton:butterknife:8.0.1' 
    apt 'com.jakewharton:butterknife-compiler:8.0.1' 
} 

Без этого нет сгенерированный код должен быть загружен и, таким образом, ни одно из полей получают задавать.

Вы можете подтвердить, что ButterKnife работает, позвоните по телефону ButterKnife.setDebug(true) и смотрите в Logcat.

+1

Большое спасибо, это работает как очарование! –

+0

Хорошо работает для меня. Это должен быть принятый ответ. – PaulT

+1

Я следил за теми же условиями readme, но для меня это не работало. это дало мне эту «Ошибка: Gradle: Execution failed for task»: app: compileWholesaleDebugJava '. > java.lang.IllegalArgumentException: не удалось сделать предположение для com.sme.Activity.fragment.AccountStatementFragment' – Min2

4
App Level(build.gradle) 

apply plugin: 'android-apt' 
dependencies { 
    compile fileTree(include: ['*.jar'], dir: 'libs') 
    compile 'com.android.support:appcompat-v7:24.2.1' 
    testCompile 'junit:junit:4.12' 
    compile 'com.jakewharton:butterknife:8.4.0' 
    apt 'com.jakewharton:butterknife-compiler:8.4.0' 
} 


Project Level(build.gradle) 

buildscript { 
    repositories { 
     jcenter() 
    } 
    dependencies { 

     classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' 
     // NOTE: Do not place your application dependencies here; they belong 
     // in the individual module build.gradle files 
    } 
} 
+0

Это решило это для меня – Oussaki

5

Я использовал эту библиотеку в Фрагменте и имеет NPE. Мой код:

ButterKnife.bind(view); 

Но это было неправильно. Библиотека необходимо знать два объекта:
1) цель - с аннотациями @BindView
2) Источник - с видом

Это будет правильно написать:

ButterKnife.bind(this, view); 

Когда это - ваш фрагмент, и view - просмотр этого фрагмента.

+0

Что делать, если это активность? –

0

От JakeWharton

Yes that plugin is no longer needed. You're already using annotationProcessor for the 'butterknife-compiler' artifact which is built-in to the Android Gradle plugin.

Тогда решение удалить меткие 'com.neenbedankt.gradle.plugins путь к классам: Android-склонный: 1.8'

1

Я тоже был этот вопрос, просто потому что я добавлен butterknife из управления зависимостями Android Studio, а не путем копирования градиентных линий с сайта Butterknife. Так что я должен был добавить compile 'com.jakewharton:butterknife:8.5.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1' вместо того, чтобы просто compile 'com.jakewharton:butterknife:8.5.1'

0
Add ` annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'` In your gradle file it worked for me 
4

для меня проблема, что я использовал

annotationProcessor 'com.jakewharton:butterknife-compiler:8.7.0' 

вместо

apt 'com.jakewharton:butterknife-compiler:8.7.0 
0

Я просто сталкивался эта проблема, после обновления моего проекта до версии Gradle 3.0.1.Я был в состоянии исправить это только в том числе в Gradle app файл строку:

annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' 

Окончательный результат был:

dependencies { 
     compile fileTree(include: ['*.jar'], dir: 'libs') 
     androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 
      exclude group: 'com.android.support', module: 'support-annotations' 
     }) 

     ... 

     compile 'com.jakewharton:butterknife:8.8.1' 
     annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' 
    } 

Я надеюсь, что это поможет кому-то, хотя этот вопрос стар.