空指针异常小部件按钮

时间:2016-06-20 13:23:41

标签: android nullpointerexception setcontentview

我正在尝试创建导航抽屉。我在MainActivity类和SecondActivityClass上扩展了BaseActivity。 虽然错误的原因是:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void   
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference  
at com.example.navigationdrawer.BaseActivity.onPostCreate(BaseActivity.java:19)

我不理解,当我在之前初始化按钮之前导致错误的原因。 `

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class BaseActivity extends AppCompatActivity {
Button inbox, address, logout;

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        inbox = (Button) findViewById(R.id.navigation_inbox);
        inbox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(BaseActivity.this, MainActivity.class));
            finish();
        }
        });
        address = (Button) findViewById(R.id.navigation_address);
        address.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(BaseActivity.this, SecondActivity.class));
                finish();
        }
        });
        logout = (Button) findViewById(R.id.navigation_logout);

        logout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(BaseActivity.this, "LoGOUT", Toast.LENGTH_SHORT).show();
            finish();
        }
        });
    }
}

0 个答案:

没有答案