Search code examples
androidonclicklistener

setonclicklistener not working on button click


when i click on button it's shwoing error of null. I don't know why stack overflow saying that this question agains the policy.

Mainactivity code

            Button bnt = findViewById(android.R.id.button1);
            bnt.setOnClickListener(new OnClickListener()

            {

                WebView web1;
                EditText editText = findViewById(android.R.id.edit);
                    public void onClick(final View view) {

                       String  Address = "http://" + editText.getText().toString();
                        web1 = (WebView) findViewById(R.id.webview);

                        WebSettings webSetting = web1.getSettings();
                        webSetting.setBuiltInZoomControls(true);
                        webSetting.setJavaScriptEnabled(true);
                        web1.setWebViewClient(new WebViewClient());
                        web1.loadUrl(Address);

                    }


            });

        }

XML Code

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:text="@string/go" />



<WebView
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginTop="50dip" />

My errors are

E/AndroidRuntime: FATAL EXCEPTION: main

                                               java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Thanks in advance


Solution

  • You are initialising your edittext and button in wrong way. You need to remove android prefix from their id

    EditText editText = findViewById(android.R.id.edit);
    

    should be

     EditText editText = findViewById(R.id.edit);
    

    and this

    Button bnt = findViewById(android.R.id.button1);
    

    should be

    Button bnt = findViewById(R.id.button1);