Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a web page on button click inside an app?

I searched over the net, and tried most of the similar topics in stackoverflow, but couldn't solve this. That's why I'm posting a question.

I want to create a very simple android application. There is a button, and if the user clicks on that button, it should open a specific website inside that application. That's it.

I've set the settings of this example project for Android 4.1.

After writing the codes, I do Build / Make Project , and then Build / Build APK , and then install this APK in my android phone (Android 7.0).

After installing and opening the app, I press the CONNECT button, but just right then, the app disappears (goes to background); it does not open the website.

Here are my codes:

MainActivity.java

package example_company.test_2;

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

public class MainActivity extends AppCompatActivity {

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

    public void goToGoogle (View view) {
        goToUrl ( "http://www.google.com/");
    }

    private void goToUrl (String url) {
        Uri uriUrl = Uri.parse(url);
        Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
        startActivity(launchBrowser);
    }

}

activity_main.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="example_company.test_2.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:text="CONNECT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/button"
        android:onClick="goToGoogle (MainActivity)" />
</RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example_company.test_2">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="http" android:host="www.google.com" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

So, what is the problem? Am I missing something !?

EDIT1

Here is the logcat errors when I press the CONNECT button, after changing the codes according to the answer from @pleft :

10-31 13:51:25.681 12178-12178/example_company.test_2 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: example_company.test_2, PID: 12178
                                                                      java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                          at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                                          at android.view.View.performClick(View.java:5646)
                                                                          at android.view.View$PerformClick.run(View.java:22459)
                                                                          at android.os.Handler.handleCallback(Handler.java:761)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                          at android.os.Looper.loop(Looper.java:156)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6531)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
                                                                       Caused by: java.lang.reflect.InvocationTargetException
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                          at android.view.View.performClick(View.java:5646) 
                                                                          at android.view.View$PerformClick.run(View.java:22459) 
                                                                          at android.os.Handler.handleCallback(Handler.java:761) 
                                                                          at android.os.Handler.dispatchMessage(Handler.java:98) 
                                                                          at android.os.Looper.loop(Looper.java:156) 
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6531) 
                                                                          at java.lang.reflect.Method.invoke(Native Method) 
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941) 
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831) 
                                                                       Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {example_company.test_2/example_company.test_2.WebViewActivity}; have you declared this activity in your AndroidManifest.xml?
                                                                          at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1850)
                                                                          at android.app.Instrumentation.execStartActivity(Instrumentation.java:1544)
                                                                          at android.app.Activity.startActivityForResult(Activity.java:4391)
                                                                          at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
                                                                          at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:75)
                                                                          at android.app.Activity.startActivityForResult(Activity.java:4335)
                                                                          at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:856)
                                                                          at android.app.Activity.startActivity(Activity.java:4697)
                                                                          at android.app.Activity.startActivity(Activity.java:4665)
                                                                          at example_company.test_2.MainActivity.goToUrl(MainActivity.java:25)
                                                                          at example_company.test_2.MainActivity.goToGoogle(MainActivity.java:19)
                                                                          at java.lang.reflect.Method.invoke(Native Method) 
                                                                          at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                                                                          at android.view.View.performClick(View.java:5646) 
                                                                          at android.view.View$PerformClick.run(View.java:22459) 
                                                                          at android.os.Handler.handleCallback(Handler.java:761) 
                                                                          at android.os.Handler.dispatchMessage(Handler.java:98) 
                                                                          at android.os.Looper.loop(Looper.java:156) 
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6531) 
                                                                          at java.lang.reflect.Method.invoke(Native Method) 
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941) 
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831) 
like image 639
Omid1989 Avatar asked Dec 11 '22 09:12

Omid1989


1 Answers

  1. Update your manifest to allow internet connection

    <uses-permission android:name="android.permission.INTERNET"/>

  2. Create the layout of your webview

webview.xml

<?xml version="1.0" encoding="utf-8"?>
    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
/>
  1. Create the WebViewActivity class

WebViewActivity

public class WebViewActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);

        Intent i = getIntent();
        String url= i.getStringExtra("url");
        WebView webView = findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        assert url != null;
        webView.loadUrl(url);
    }
}
  1. Update your MainActivity.goToUrl code to the following:

    private void goToUrl (String url) { Intent intent = new Intent(this, WebViewActivity.class); intent.putExtra("url", url); startActivity(intent); }

  2. Change in your activity_main.xml the line:

    android:onClick="goToGoogle (MainActivity)"

to

android:onClick="goToGoogle"
  1. To resolve the error in the logcat stacktrace posted in the question, the new activity must be declared in the manifest. So just above the line

add the following:

<activity android:name=".WebViewActivity" android:theme="@android:style/Theme.NoTitleBar"/>
  1. If you use webView.getSettings().setJavaScriptEnabled(true); it will lead to a warning that setJavaScriptEnabled can introduce XSS vulnerabilities into your application, so review carefully! Or you can simply remove it if you don't want to use JS in your webview.

UPDATE

The final working codes look like the following:

MainActivity.java

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

public class MainActivity extends AppCompatActivity {

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

    public void goToGoogle (View view) {
        goToUrl ( "http://www.google.com/");
    }

    private void goToUrl (String url) {
        Intent intent = new Intent(this, WebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("name", "Your Title Name");
        startActivity(intent);
    }

}

WebViewActivity.java

package example_company.test_2;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;

public class WebViewActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);

        Intent i = getIntent();
        String url= i.getStringExtra("url");
        WebView webView = findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        assert url != null;
        webView.loadUrl(url);

        TextView textView = findViewById(R.id.name);
        textView.setText(i.getStringExtra("name"));
        textView.setOnClickListener(v -> finish());

        ImageButton imageButton = findViewById(R.id.backbtn);
        imageButton.setOnClickListener(v -> finish());
    }
}

activity_main.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="example_company.test_2.MainActivity">

    <Button
        android:text="CONNECT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/button"
        android:onClick="goToGoogle"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1" />

</RelativeLayout>

webview.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".WebViewActivity">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimaryDark"
        android:theme="@style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:popupTheme="@style/MenuStyle">

        <ImageButton
            android:id="@+id/backbtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/ic_arrow_back_black_24dp"
            android:contentDescription="Back"
            tools:ignore="HardcodedText" />

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_marginStart="10dp"
            android:layout_marginLeft="10dp"
            android:textColor="#fff"
            android:textSize="18sp"
            android:textStyle="bold" />
    </androidx.appcompat.widget.Toolbar>


    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar" />

</androidx.constraintlayout.widget.ConstraintLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example_company.test_2">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".WebViewActivity" android:theme="@android:style/Theme.NoTitleBar"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Screenshot:

enter image description here

like image 100
pleft Avatar answered Jan 07 '23 10:01

pleft