尝试在空对象引用上调用虚方法,但该对象不为null

时间:2016-06-13 21:09:07

标签: java android

我甚至在这里搜索过这个错误,但没有解决它。所以我希望我的案子和看起来一样独特...... 这是我的app的AndroidManifest.xml:

apply plugin: 'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion "23.0.3"

defaultConfig {
    applicationId "dell.example.com.myapp"
    minSdkVersion 15
    targetSdkVersion 21
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.android.support:design:23.1.0'
}

这是MainActivity.java类的第一部分:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {


@Bind(R.id.tagEditText)
EditText storyTag;

@Bind(R.id.user_name)
TextView username;

@Bind(R.id.drawer_layout)
DrawerLayout drawer;

@Bind(R.id.nav_view)
NavigationView navigationView;

@Bind(R.id.storyTableLayout)
TableLayout storyTableLayout; 

@Bind(R.id.toolbar)
Toolbar toolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    setSupportActionBar(toolbar);
    clearTags(); // Clear all tags to load an updated copy from the database
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle); **// THIS IS WHERE IT CRASHES**
    toggle.syncState();
    username.setText(user.getName());
    navigationView.setNavigationItemSelectedListener(this);
    refreshStories(); // add previously saved story tags to GUI
}

我在MainActivity之前有2个其他活动,并且使用任何声明的视图都没有抛出空异常!!!! 即使我这样声明:

类变量:

EditText storyTag;
onCreate()中的

storyTag = (EditText) findViewById(R.id.tagEditText) 

例如,如果我说:

storyTag.setText("Hello");

它会引发同样的异常,如下所示:

java.lang.RuntimeException: Unable to start activity ComponentInfo{dell.example.com.myapp/dell.example.com.myapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.addDrawerListener(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference
.
.
.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.addDrawerListener(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference

所有xml布局都存在相同的id名称,而R.java包含相同的ID !!!!

我不知道如何解决这个问题..请帮助!

1 个答案:

答案 0 :(得分:1)

@Bind并非自动发生,您必须将其称为:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);  <<< THIS LINE