-1

My webview app works on the emulator and my phone but crashes when I insert the code below inside onCreate (based from the answers here) which supposedly enable the zoom controls.

myWebView.getSettings().setBuiltInZoomControls(true);

Other codes I tried(same result):

 myWebView.getSettings().setSupportZoom(true);
 myWebView.getSettings().setBuiltInZoomControls(true);
 myWebView.getSettings().setDisplayZoomControls(false);

Here's my MainActivity:

package com.example.androidbrowser;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {


private WebView myWebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    getSupportActionBar().hide();

    myWebView.getSettings().setBuiltInZoomControls(true);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myWebView = (WebView) findViewById(R.id.activity_main_webview);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    myWebView.loadUrl("http://192.168.43.105/public_html/central/updates.php");
    myWebView.setWebViewClient(new WebViewClient());

    myWebView.setWebViewClient(new WebViewClient() {
     public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
         Toast.makeText(MainActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();

     }
     public void onPageFinished(WebView webView, String url) {
       CookieManager.getInstance().flush();
     }
  }
    );
}
@Override
public void onBackPressed() {
    if (myWebView.canGoBack()) myWebView.goBack();
    else super.onBackPressed();
}


}

Thanks!

ADM
  • 20,406
  • 11
  • 52
  • 83
  • 1
    Though you have not mentioned any crash logs , I'm guessing it's a NPE, You are using `myWebView` before even finding it's view. Set zoom controls after finding the id of webview. – Nitish Dec 10 '21 at 04:47
  • you should be accessing the view only after `setContentView(R.layout.activity_main)`. – ADM Dec 10 '21 at 05:12

1 Answers1

0

Fixed the issue by inserting this code

myWebView.getSettings().setBuiltInZoomControls(true);

at the end of onCreate method.

  protected void onCreate(Bundle savedInstanceState) {
  . . . . . . . 
    myWebView.getSettings().setBuiltInZoomControls(true);
}

Thanks to @ADM for the hint.