Android Tutorial: Launch URL based on an OnClickListener

As a beginner in Android you spent often a long time on something very simple ;). Often because you miss some crucial knowledge, but don’t get frustrated, my experience is that you learn different concepts along the way and it becomes easier and easier to find solutions to problems you did’t solve before. In this short blog post I show you how you can launch an URL (website) based on OnClickListener event (for e.g. Button Click).

Assuming you have set in the Layout a  button or other relevant widget you have to set the following Java in your Activity:

Please note that I have set my URL as a global variable in the MainActvity class and them parse the URL in the Intent method of the OnClickListener.

package com.example.launchwebsite;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

String url1 = "http://m.nu.nl";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button btnlaunchwebsite = (Button)findViewById(R.id.button1);
        
        btnlaunchwebsite.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url1));
                startActivity(i);
			}
		});
        
    }

    
}

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*