简体   繁体   中英

null pointer exception when adding an onclicklistener to a button outside the main view

I want to have access to objects in views from views other than the main content view in the app. How can I go about doing this?

I am trying to add an onclicklistener, but it fails every time because the program can't seem to find the button.

02-12 15:26:29.034: E/AndroidRuntime(11788): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.evolutionsystems.kiroco/com.evolutionsystems.kiroco.OverviewActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Or am I going about this the wrong way? Should I include all the buttons in the main view and have them set to hidden and then change them dynamically as the user interacts with the program?

EDIT - This is the type of code that throws the error.

final Button receiver = (Button) findViewById(R.id.receiver);   
         receiver.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 aboutKirocoClicked(v);
             }
         }); 

The receiver button is part of a different view to the content view so the program can't find it and it returns null.

When you call findViewById( int ) you are asking for a view within the context of the object you called.

So if this is an activity then the object must be part of the xml resource from setContent.

You can also find resources from other inflated layouts ( menu, fragement ), but you must call the findViewById on that object inorder to find the view.

Not to complicate your life, but once you are more comfortable with Android you may want to check out a dependency injection framework like Roboguice or Dagger.

In your Activity, where you would like your button to appear, you add the following code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //In activity_main.xml, you have a button.
    setContentView(R.layout.activity_main);
    //You get this button with the referencing ID
    Button myBtn = (Button) findViewById(R.id.my_btn_id);
    //Now, you can set your onClickListner
    myBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Handle your button click
        }
    });
}

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