'open a URL link on click of ok button in android studio
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
f.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = "https://www.google.co.uk/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
//This is what i have so far but it is not loading the URL on the emulator it keeps coming up with:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener((android.view.View$OnClickListener)' on a null object reference
I have tried most things and i cant figure it out for the life of me any help would be appreciated
Solution 1:[1]
This is because you have not initialised your f button. did you initialise it with f = (Button) findViewById(R.id.yourButton);? It is complaining that your button is null
Solution 2:[2]
Use -
(findViewById(R.id.Fire)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = "https://www.google.co.uk/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
Solution 3:[3]
I have done that (sorry not in initial code), yes it is coming back saying:
android.view.View$OnClickListener)' on a null object reference
ACTUAL CODE
Button f = (Button) findViewById(R.id.Fire);
f.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = "https://www.google.co.uk/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joel Min |
| Solution 2 | Shadab Ansari |
| Solution 3 | Adam |
