您好我在这里面临一个非常奇怪的问题。我已经使用依赖注入(Butterknife)来为BindViews而不是写锅炉板代码来每次都实现视图。有时它可以解决问题,有时只会产生NullpointerException
,因为它不会编译我认为的视图。
我的app模块(build.gradle):
apply plugin: 'com.android.application'
repositories {
maven { url "https://jitpack.io" }
}
android {
compileSdkVersion 25
buildToolsVersion "25.0.1"
defaultConfig {
applicationId "com.example.androidnative.testproject"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
jackOptions {
enabled true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
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 project(':mylibrary')
compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.android.support:design:25.0.1'
compile 'com.android.support:support-v4:25.0.1'
compile 'com.android.support:cardview-v7:25.0.1'
compile 'com.android.support:recyclerview-v7:25.0.1'
compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
compile 'com.koushikdutta.ion:ion:2.1.9'
testCompile 'junit:junit:4.12'
}
和我使用的活动:
public class MainActivity extends AppCompatActivity{
@BindView(R.id.bottomBar) BottomNavigationView bottomNavigationView;
private Fragment fragment;
private FragmentManager fragmentManager;
private FragmentTransaction transaction;
private RestService service;
@BindView(R.id.toolbar) Toolbar toolbar;
private List<DummyJSONModel> modelFromJson = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
ButterKnife.setDebug(true);
setupToolbar();
setupBottomBar();
service = new RestService();
DummyJSONModelWrapper wrapper = (DummyJSONModelWrapper)getIntent().getSerializableExtra(AppConstants.INTENT_KEY);
modelFromJson = wrapper.getDummyJSONModel();
}
private void setupToolbar() {
toolbar.setTitle(getString(R.string.app_name));
setSupportActionBar(toolbar);
}
}
有时我会收到NullpointereException,错误消息为:
cannot android.support.v7.widget.Toolbar.setTitle() on a null object reference
为什么会发生这种情况?