Error clicking a button to access site

2

I tried to make the user click on a particular button, it was directed to a website, in this case google, but it did not work.

The app starts normally, but when you click the button the app stops at nothing:

Thisappearsintheeventlog:

NullPointerException:Errorexecutingtaskcom.android.tools.idea.uibuilder.editor.NlPreviewForm$$Lambda$186/56197713@4193ab80

MainActivity.java:

package genesysgeneration.bb;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button btnSite;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnSite=(Button)findViewById(R.id.btnsite);
        btnSite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse("www.google.com"));
                startActivity(it);

            }
        });

    }

}

xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="genesysgeneration.bb.MainActivity">

    <Button
        android:text="Coisas de maxo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnsite"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>
    
asked by anonymous 14.01.2017 / 01:04

1 answer

1

You need to add http:// to your link . Here's how it should look:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://google.com"));
startActivity(browserIntent);

See more in the Intent documentation.

You can improve your code by creating a method for checking http and https . See:

private static final String HTTPS = "https://";
private static final String HTTP = "http://";

public static void abrirNavegador(final Context context, String url) {

     if (!url.startsWith(HTTP) && !url.startsWith(HTTPS)) {
            url = HTTP + url;
     }

     Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
     context.startActivity(Intent.createChooser(intent, "Choose browser"));    
}
    
14.01.2017 / 01:26