Null Pointer Exception in button function

2020-04-16 06:37发布

Button btnEditor;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    btnEditor = (Button) findViewById(R.id.btnEditor);

    //some code

    btnEditor.setOnClickListener(new View.OnClickListener(){
        public void onClick(View arg0) {

        }
    });
}

btnEditor.setOnClickListener(new View.OnClickListener() gives me a Null Pointer Exception. btnEditor is earlier connecter to XML Button by: btnEditor = (Button) findViewById(R.id.btnEditor);

In my main.xml file:

<Button
        android:id="@+id/btnEditor"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="16dp"
        android:text="Editor"
        android:textSize="48dp"
        android:textStyle="bold"
        android:typeface="normal" android:layout_gravity="bottom"/>

Seriously, I have no idea what to do...

RESOLVED

I forgot that I had two main.xml files:

  • /res/layout
  • /res/layout-large

One of them (in large dir) didn't contain a Button inside, so I got an error while running application on device using large layout.

标签: java android xml
3条回答
闹够了就滚
2楼-- · 2020-04-16 06:47

write this as global variable

Button btnEditor ;

in your on create() write

btnEditor = (Button) findViewById(R.id.btnEditor);
btnEditor.setOnClickListener(new View.OnClickListener(){
        public void onClick(View arg0) {

        }
    });
查看更多
Evening l夕情丶
3楼-- · 2020-04-16 06:52

try to do next:

  1. btn.setOnclickListener(this);
  2. Your class name implemented OnclickListener
  3. Add Method OnClick
  4. @Override public void onClick(View v) { switch (v.getId()) { case R.id.R.id.btnEditor: your code break; }}
查看更多
▲ chillily
4楼-- · 2020-04-16 06:53

Most likely you haven't called setContentView() with the layout that this Button is in or else you haven't called setContentView() before this line

btnEditor = (Button) findViewById(R.id.btnEditor);

either of these situations would give a NPE at that line and would be the only reason for it. If you think you are then please post how you are doing this.

查看更多
登录 后发表回答