简体   繁体   中英

Null Pointer Exception in button function

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.

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.

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; }}

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) {

        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM