0

I'm new on Android studio.

Please review my code

Problem- when i click on any activity below maintained then it opens in an external browser instead of loading in same webview. so please suggest me how to load url in same webview instead of browser.

i have added some codes to stop opening external browser but it doesn't works fine.

package com.hanumanbeniwal.www.hanumanbeniwal;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.KeyEvent;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;


import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import java.net.URI;

import static com.hanumanbeniwal.www.hanumanbeniwal.R.id.progressBar2;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    //initializing WebView
    private WebView mwebView;
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);



        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
        //WebView
        mwebView = (WebView) findViewById(R.id.myWebView);
        WebSettings webSettings = mwebView.getSettings();



        //improve webView performance
        mwebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        mwebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        mwebView.getSettings().setAppCacheEnabled(true);
        mwebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setUseWideViewPort(true);
        webSettings.setSavePassword(true);
        webSettings.setSaveFormData(true);
        webSettings.setEnableSmoothTransition(true);
        mwebView.getSettings().setDomStorageEnabled(true);

        //force links open in webview only
        mwebView.setWebViewClient(new MyWebviewClient());
        webSettings.setJavaScriptEnabled(true);
        mwebView.loadUrl("http://www.hanumanbeniwal.com");

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_home) {
            // Handle the camera action
            mwebView.loadUrl("http://www.hanumanbeniwal.com/home");
        } else if (id == R.id.nav_video) {
            mwebView.loadUrl("https://www.youtube.com/channel/UCoQcL7eGvx8462O3-Jef-Cg/");
        } else if (id == R.id.nav_news) {
            mwebView.loadUrl("https://m.facebook.com/hanumanbeniwal/");
        } else if (id == R.id.nav_images) {
            mwebView.loadUrl("https://m.facebook.com/hanumanbeniwal/photos/");
        } else if (id == R.id.nav_biography) {
            mwebView.loadUrl("http://www.hanumanbeniwal.com/home");
        }  else if (id == R.id.nav_contact) {
            mwebView.loadUrl("http://www.hanumanbeniwal.com/contact-us/");
        }
         else if (id == R.id.nav_complaint) {
            mwebView.loadUrl("http://www.google.com");
        } else if (id == R.id.nav_suggestion) {
            mwebView.loadUrl("http://www.google.com");
        }


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private class MyWebviewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals("www.hanumanbeniwal.com")) {
                //open url contents in webview
                return false;
            } else {
                //here open external links in external browser or app
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            }

        }
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            super.onPageStarted(view, url, favicon);
            findViewById(R.id.progressBar2).setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            findViewById(R.id.progressBar2).setVisibility(View.GONE);
        }

    }
    //goto previous page when pressing back button

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (mwebView.canGoBack()) {
                        mwebView.goBack();
                    } else
                    {
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setMessage("Are you sure you want to exit?")
                                .setCancelable(false)
                                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        finish();
                                    }
                                })
                                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
                    return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}

3 Answers3

1

You can try to put the video in an iFrame, then use the loadData method instead loadUrl

String frameVideo = "<html><body>Video From YouTube<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/channel/UCoQcL7eGvx8462O3-Jef-Cg\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
mwebView.loadData(frameVideo, "text/html", "utf-8");
ludwiguer
  • 2,177
  • 2
  • 15
  • 21
0

Inside webView:

 webview.apply{
settings.javaScriptEnabled = true
settings.loadWithOverviewMode = true
settings.useWideViewPort = true
webViewClient = MyClient()
loadUrl("http://www.naver.com")
 }


inner class MyClient : WebViewClient() {
    override fun shouldOverrideUrlLoading(view: WebView?, request: 
           WebResourceRequest?): Boolean {
        view?.loadUrl(request?.url?.toString())
        return true
    }
}

This answer was given to my 13 days ago by @pistolcaffe and it perfectly worked, I hope this is still usefull for you.

-1

instead of

if (Uri.parse(url).getHost().equals("www.hanumanbeniwal.com")) {

try using contain or containsIgnoreCase

if (Uri.parse(url).getHost().containsIgnoreCase("www.hanumanbeniwal.com")) {

or simply

if(url.containsIgnoreCase("www.hanumanbeniwal.com"))

Intercept and override HTTP requests from WebView

skryshtafovych
  • 572
  • 4
  • 16
  • Error - Cannot resolve symbol '' containsIganoreCase '' – Hanu Choudhary Sep 08 '17 at 19:36
  • you misspelled ignore... you have to use apache common lib...or if you dont want to do that that just do contains if you know you url will always be lowercase otherwise set string to all lowercase than do contains.[take a look here](https://stackoverflow.com/questions/14018478/string-contains-ignore-case) – skryshtafovych Sep 08 '17 at 23:10