WebView not loading url in Android 4.4+ - android

I have one issue with WebView, one link that simply loads in WebView but it's not working.
The same URL is working fine with versions 4.1, 4.2,4.2.2, and 4.3 of Android OS, but it's not working in versions 4.4 and above.
Url is http://rise.esprit-apps.com/faqs/mobilefaq
That means it's not working in Kitkat, Lollipop, or Marshmallow.
I think it's a cookies problem, but I have enabled cookies in WebView but can't resolve this.
The same URL is working in Chrome and another browser perfectly but it's not loading in default WebView.
If anyone has a solution, please let me know.
Here is my code:
package com.avm.ui;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.avm.uc.CustAnimatedActivity;
import com.avm.uc.CustomProgressBarDialog;
import com.avm.uc.Header;
import com.avm.util.Config;
import com.avm.util.Pref;
import com.avm.util.Utils;
import com.esp.therisemethod.R;
public class EvaluateYourSelfEsteemActivity extends CustAnimatedActivity {
/* Declaration of variable here */
private Header header;
private WebView webView;
private CustomProgressBarDialog mProgressDialog;
private int flag;
private DefaultHttpClient httpClient;
public static Cookie cookie = null;
// Flag 1=for EvaluateYourSelfEsteem
// Flag 2=for Faq
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_common_webview);
flag = getIntent().getIntExtra("FLAG", 0);
Utils.addActivities(EvaluateYourSelfEsteemActivity.this);
/* fetch object resource here */
header = (Header) findViewById(R.id.header);
/* setValue in Header */
if (flag == 1) {
header.txtTitle.setText(getResources().getString(
R.string.RATE_YOUR_SELF_ESTEEM));
} else if (flag == 2) {
header.txtTitle.setText(getResources().getString(R.string.FAQs));
} else if (flag == 3) {
header.txtTitle.setText(getResources().getString(
R.string.PREMIUM_ACCOUNT));
}
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.clearHistory();
webView.clearView();
WebSettings settings = webView.getSettings();
settings.setDefaultTextEncodingName("utf-8");
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccess(true);
settings.setLoadWithOverviewMode(true);
settings.setPluginState(PluginState.ON);
settings.setRenderPriority(RenderPriority.HIGH);
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
settings.setDomStorageEnabled(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setDisplayZoomControls(false);
settings.setUseWideViewPort(false);
if (Build.VERSION.SDK_INT >= 21) {
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
cookieManager.setAcceptThirdPartyCookies(webView, true);
cookieManager.setAcceptCookie(true);
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
}
webView.setBackgroundColor(Color.TRANSPARENT);
if (Utils.isTablet(EvaluateYourSelfEsteemActivity.this))
settings.setTextSize(WebSettings.TextSize.LARGER);
else
settings.setTextSize(WebSettings.TextSize.NORMAL);
/** set background layer */
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
}
if (flag == 1) {
webView.loadUrl("http://www.riseselfesteem.com/test/");
} else if (flag == 2) {
webView.loadUrl("http://192.168.1.42/work/rise/faqs/mobilefaq");
// webView.loadUrl("http://rise.esprit-apps.com/faqs/mobilefaq");
} else if (flag == 3) {
webView.loadUrl("http://192.168.1.42/work/rise/payments/mobilepay/"
+ Pref.getValue(EvaluateYourSelfEsteemActivity.this,
Config.PREF_USERID, "0"));
}
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (mProgressDialog == null) {
mProgressDialog = new CustomProgressBarDialog(
EvaluateYourSelfEsteemActivity.this);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
}
}
// load URL
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.equals("http://www.riseselfesteem.com/video")) {
view.stopLoading();
startAnimatedActivity(new Intent(
EvaluateYourSelfEsteemActivity.this,
AboutUsActivity.class),
CustAnimatedActivity.SLIDE_FROM_RIGHT);
return false;
} else if (url
.equals("http://192.168.1.42/work/rise/contact?mobilecontact")) {
view.stopLoading();
startAnimatedActivity(new Intent(
EvaluateYourSelfEsteemActivity.this,
ContectUsActivity.class),
CustAnimatedActivity.SLIDE_FROM_RIGHT);
return false;
} else if (url.equals("http://paymentfail/")) {
view.stopLoading();
finish();
overridePendingTransition(
R.anim.animated_activity_slide_left_in,
R.anim.animated_activity_slide_right_out);
return false;
} else if (url.equals("http://paymentdone/")) {
view.stopLoading();
Pref.setValue(EvaluateYourSelfEsteemActivity.this,
Config.PREF_IS_PAID, "1");
startAnimatedActivity(new Intent(
EvaluateYourSelfEsteemActivity.this,
PremiumAccountSucessActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
CustAnimatedActivity.SLIDE_FROM_RIGHT);
finish();
return false;
} else {
view.loadUrl(url);
return true;
}
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.cancel();
mProgressDialog = null;
}
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.cancel();
mProgressDialog = null;
}
}
});
super.onCreate(savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the state of the WebView
webView.saveState(outState);
}
// onRestoreInstanceState to restore the instance
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the state of the WebView
webView.restoreState(savedInstanceState);
}
#SuppressWarnings("deprecation")
#Override
public void onDestroy() {
try {
webView.clearView();
} catch (Exception e) {
e.printStackTrace();
}
super.onDestroy();
}
#Override
protected void onPause() {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
mProgressDialog = null;
super.onPause();
}
#Override
public void onBackPressed() {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
mProgressDialog = null;
super.onBackPressed();
}
}
I got below Error in logcat:
12-31 10:29:11.223: I/art(11886): Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.FloatingSelectActionModeCallback>
12-31 10:29:11.228: I/art(11886): Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.FloatingSelectActionModeCallback>
12-31 10:29:11.246: I/art(11886): Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.WebViewContentsClientAdapter$WebResourceErrorImpl>
12-31 10:29:11.247: I/art(11886): Rejecting re-init on previously-failed class java.lang.Class<com.android.webview.chromium.WebViewContentsClientAdapter$WebResourceErrorImpl>
Thank you.

Please Check Migrating to WebView in Android 4.4
Android 4.4 (API level 19) introduces a new version of WebView that is based on Chromium. This change upgrades WebView performance and standards support for HTML5, CSS3, and JavaScript to match the latest web browsers. Any apps using WebView will inherit these upgrades when running on Android 4.4 and higher.
Reference Link: http://developer.android.com/guide/webapps/migrating.html
Hope it will help you.

Try this code:
CookieManager cm = CookieManager.getInstance();
cm.setAcceptCookie(true);
It should be executed before WebView is created.

Related

Looks like you are using an older version of supported browser (Bigbluebutton)

I am developing a webview application to run BigBlueButton website on my app for video conferencing. I am facing an error "Looks like you are using an older version of supported browser. Please upgrade Your browser for full support" with blue screen. As I am new in android development. Please help...
My code is
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.http.SslError;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static WebView webView;
private static ProgressBar webViewProgressBar;
private static ImageView back, forward, refresh, close;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
setUpWebView();
setListeners();
}
private void initViews() {
back = (ImageView) findViewById(R.id.webviewBack);
forward = (ImageView) findViewById(R.id.webviewForward);
refresh = (ImageView) findViewById(R.id.webviewReload);
close = (ImageView) findViewById(R.id.webviewClose);
webViewProgressBar = (ProgressBar) findViewById(R.id.webViewProgressBar);
}
private void setUpWebView() {
webView = (WebView) findViewById(R.id.sitesWebView);
webView.setWebViewClient(new MyWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
String value = getIntent().getStringExtra("uid");
final String webViewUrl = "http://www.google.com";
LoadWebViewUrl(webViewUrl);
}
private void setListeners() {
back.setOnClickListener(this);
forward.setOnClickListener(this);
refresh.setOnClickListener(this);
close.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.webviewBack:
isWebViewCanGoBack();
break;
case R.id.webviewForward:
if (webView.canGoForward())
webView.goForward();
break;
case R.id.webviewReload:
String url = webView.getUrl();
LoadWebViewUrl(url);
break;
case R.id.webviewClose:
finish();
break;
}
}
public void homeclick(View view) {
Intent intent= new Intent(MainActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
public class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
refresh.setVisibility(View.GONE);
if (!webViewProgressBar.isShown())
webViewProgressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
refresh.setVisibility(View.VISIBLE);
if (webViewProgressBar.isShown())
webViewProgressBar.setVisibility(View.GONE);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
refresh.setVisibility(View.VISIBLE);
if (webViewProgressBar.isShown())
webViewProgressBar.setVisibility(View.GONE);
}
#Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
refresh.setVisibility(View.VISIBLE);
if (webViewProgressBar.isShown())
webViewProgressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "Fetching data.", Toast.LENGTH_SHORT).show();
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
super.onReceivedSslError(view, handler, error);
refresh.setVisibility(View.VISIBLE);
if (webViewProgressBar.isShown())
webViewProgressBar.setVisibility(View.GONE);
}
}
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
isWebViewCanGoBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void isWebViewCanGoBack() {
if (webView.canGoBack())
webView.goBack();
else
finish();
}
private void LoadWebViewUrl(String url) {
if (isInternetConnected())
webView.loadUrl(url);
else {
refresh.setVisibility(View.VISIBLE);
}
}
public boolean isInternetConnected() {
// At activity startup we manually check the internet status and change
// the text status
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
}
[1]: https://i.stack.imgur.com/pc5sh.jpg
you can add user agent like this
webView.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36");
and also add MODIFY_AUDIO_SETTINGS permission into androidManifest.xml
For iOS and Swift
I added this line of code and it will works fine with me.
Add it in viewDidLoad
myWKWebView.customUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36"

WebView attributes like setJavaScriptEnabled,setBuiltInZoomControls etc. are not being saved

The features are enabled once the onCreate() methood is executed for the first time, but after i do a screen rotation none of the features get saved, even though I've overridden the onSaveInstanceState() method and I've also tried using the onRestoreInstanceState() method.
Kindly help me out.
I'll attach the code below.
Activity file
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.Loader;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class Main3Activity extends AppCompatActivity implements LoaderManager.LoaderCallbacks{
Toolbar toolbar;
WebView webView;
ProgressDialog progressDialog;
final String urld="https://www.google.co.in/";
final int LOADER_ID=1;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
webView = (WebView)findViewById(R.id.wb1);
progressDialog = new ProgressDialog(Main3Activity.this);
progressDialog.setTitle("Loading");
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Please Wait...");
progressDialog.setCancelable(true);
if(savedInstanceState!=null)
{
webView.restoreState(savedInstanceState);
webView.getSettings().setJavaScriptEnabled(true);
}
else {
webView.getSettings().setJavaScriptEnabled(true);
webView.setFocusable(true);
webView.setFocusableInTouchMode(true);
//webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//webView.setInitialScale(1);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setBackgroundColor(Color.WHITE);
//webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setDomStorageEnabled(true);
//webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
//webView.setWebChromeClient(new WebChromeClient());
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
/*if( URLUtil.isNetworkUrl(url) ) {
return false;
}
if (appInstalledOrNot(url)) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity( intent );
} else {
// do something if app is not installed
}
return true;*/
if (Uri.parse(url).getHost().endsWith("google.co.in")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
CookieManager.getInstance().setAcceptCookie(true);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressDialog.show();
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
progressDialog.dismiss();
super.onPageFinished(view, url);
}
});
}
bundle = savedInstanceState;
LoaderManager loaderManager = getLoaderManager();
// Initialize the loader. Pass in the int ID constant defined above and pass in null for
// the bundle. Pass in this activity for the LoaderCallbacks parameter (which is valid
// because this activity implements the LoaderCallbacks interface).
loaderManager.initLoader(LOADER_ID, null, this);
}
/*private boolean appInstalledOrNot(String uri) {
PackageManager pm = getPackageManager();
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}*/
#Override
public void onBackPressed() {
if(webView.canGoBack())
{
webView.goBack();
}
else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
#Override
public Loader onCreateLoader(int i, Bundle bundle) {
return new LoadingPageInBackground(this,urld,bundle,webView,progressDialog);
}
#Override
public void onLoadFinished(Loader loader, Object o) {
}
#Override
public void onLoaderReset(Loader loader) {
//webView.setVisibility(WebView.GONE);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
webView.saveState(outState);
Toast.makeText(Main3Activity.this,"Saved",Toast.LENGTH_SHORT).show();
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
webView.restoreState(state);
Toast.makeText(Main3Activity.this,"Restored",Toast.LENGTH_SHORT).show();
super.onRestoreInstanceState(state);
}
}
restoreState is not reliable, based on the documentation for restoreState :
If it is called after this WebView has had a chance to build state
(load pages, create a back/forward list, etc.) there may be
undesirable side-effects. Please note that this method no longer
restores the display data for this WebView.
Based on the documentation for saveState:
Please note that this method no longer stores the display data for
this WebView
You have to reload your WebView in onCreate(). You can store the URL in SharedPreference and load it in onCreate().
Another alternative is to handle the Orientation by your self and keep WebView unchanged. You can handle the orientation change by adding android:configChanges="orientation" in your manifest and Overriding onConfigurationChanged().

How to Load Cache Page in Webview

I have Cache Manifest applied on HTML Page.
On Chrome Browser when Internet connection goes off, it redirects to cache mode.
Well, this is not the case with Android-Webview. It gives following error:
Webpage could not be loaded
net:ERR_NAME_NOT_RESOLVED
Have gone through various resources but none seems to help.
Below is the code am using:
package com.example.page;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.google.firebase.iid.FirebaseInstanceId;
public class MainActivity extends Activity {
public static WebView mWebview;
private android.content.Context Context;
private static String getIntentValue = null;
public static SharedPreferences sharedPreferences;
private ProgressDialog mProgressDialog;
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
private final static int FCR=1;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
mWebview.setWebViewClient(new Callback());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context = this;
String regId = FirebaseInstanceId.getInstance().getToken();
getIntentValue = getIntent().getStringExtra("value");
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet Connection!", Toast.LENGTH_LONG).show();
finish(); //Calling this method to close this activity when internet is not available.
} else {
mWebview = (WebView) findViewById(R.id.webview1);
WebSettings webSettings = mWebview.getSettings();
mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.setWebChromeClient(new WebChromeClient());
mWebview.setWebViewClient(new CustomWebViewClient());
//improve WebView Performance
mWebview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mWebview.getSettings().setAppCacheEnabled(false);
mWebview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
if(Build.VERSION.SDK_INT >=23 && (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}, 1);
}
mWebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setAllowFileAccess(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
// progress dialog
mProgressDialog = new ProgressDialog(Context);
if (sharedPreferences.getBoolean("isKeyGenerated", true)) {
if (getIntentValue != null) {
mWebview.loadUrl("http://www.example.com/page");
getIntentValue = null;
} else {
mWebview.loadUrl("http://www.example.com/page2");
}
}
}
}
public class Callback extends WebViewClient{
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
}
}
// Function to load all URLs in same webview
private class CustomWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains(".pdf")) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
//on page started, show loading page
mProgressDialog.setCancelable(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.show();
}
#Override
public void onPageFinished(WebView view, String url)
{
String currentPage= mWebview.getUrl();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("currentpage",currentPage);
editor.commit();
//after loading page, remove loading page
// TODO Auto-generated method stub
super.onPageFinished(view, url);
mProgressDialog.dismiss();
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
view.loadUrl("http://example.com/page");
}
}
#Override
public void onBackPressed() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String currenturl = sharedPreferences.getString("currentpage", null);
mWebview.requestFocus();
if (currenturl.contains("http://example.com/page")){
moveTaskToBack(true);
}else{
mWebview.goBack();
}
if (mWebview.canGoBack()) {
if (!DetectConnection.checkInternetConnection(Context)) {
Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show();
}
}
}
public static void loadUrl(String key) {
if (getIntentValue != null) {
mWebview.loadUrl("http://example.com/page");
getIntentValue = null;
} else {
mWebview.loadUrl("http://example.com/page");
}
}
public static void reLoad() {
mWebview.reload();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
}
Just include enableHTML5AppCache()
private void enableHTML5AppCache() {
mWebview.getSettings().setDomStorageEnabled(true);
mWebview.getSettings().setAppCachePath("/data/data/" + getPackageName() + "/cache");
mWebview.getSettings().setAppCacheEnabled(true);
mWebview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
mWebview.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK)
This will tell the WebView to load the page from cache, but if it needs anything that isn't in the cache, it looks to the network, and when you have no connection, it will just give you the "page could not be loaded error." This is because sadly not everything is stored in the cache and even with this setting, you will notice the browser using the network.
Use WebSettings.LOAD_CACHE_ONLY
mWebview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY);
Change this line:
mWebview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
To:
mWebview.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK)
2021 update things have changed : Deprecated
The Application Cache API is deprecated and this method will become a no-op on all Android versions once support is removed in Chromium. Consider using Service Workers instead. See https://web.dev/appcache-removal/ for more information.
Read about service workers instead :) Happy Coding :P

Webview - Open links in external browser?

Can anyone help me in opening specific link in External browser or other android app?
For Example if URL matches whatsapp:// then it should open link in WhatsApp app and if WhatsApp is not installed then it should open https://play.google.com/store/apps/details?id=com.whatsapp in android browser.
FYI: I am using https://github.com/SurfEdge/flarum-mobile-android to create Web View App for my Forum website.
My Android code looks like:
package com.example.example;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import im.delight.android.webview.AdvancedWebView;
public class MainActivity extends AppCompatActivity implements AdvancedWebView.Listener{
public AdvancedWebView webView;
private ProgressBar mPbar = null;
private static final String url = "https://example.com/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mPbar = (ProgressBar) findViewById(R.id.loader);
webView = (AdvancedWebView) findViewById(R.id.newWeb);
webView.loadUrl(url);
webView.setListener(this, this);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
webSettings.setAllowFileAccess(true);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
AdvancedWebView newWebView = new AdvancedWebView(MainActivity.this);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
webSettings.setAllowUniversalAccessFromFileURLs(true);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
mPbar.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url) {
mPbar.setVisibility(View.GONE);
}
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("whatsapp://")) {
final Uri uri = Uri.parse("market://details?id=com.whatsapp");
final Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
#SuppressWarnings({"NewApi", "deprecation"})
final int newDocumentFlag = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) ? Intent.FLAG_ACTIVITY_NEW_DOCUMENT : Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | newDocumentFlag | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException ex) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.whatsapp")));
}
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
});
webView.setOnKeyListener( new View.OnKeyListener() {
#Override
public boolean onKey( View v, int keyCode, KeyEvent event ) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return false;
}
});
webView.setThirdPartyCookiesEnabled(true);
webView.setCookiesEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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);
}
#Override
protected void onResume() {
super.onResume();
webView.onResume();
}
#Override
protected void onPause() {
webView.onPause();
super.onPause();
}
#Override
protected void onDestroy() {
webView.onDestroy();
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
webView.onActivityResult(requestCode, resultCode, intent);
}
#Override
public void onBackPressed() {
if (!webView.onBackPressed()) { return; }
super.onBackPressed();
}
#Override
public void onPageStarted(String url, Bitmap favicon) {
}
#Override
public void onPageFinished(String url) {
}
#Override
public void onPageError(int errorCode, String description, String failingUrl) {
}
#Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
}
#Override
public void onExternalPageRequest(String url) {
}
}
Error:
Error:(86, 11) error: cannot find symbol class Uri
Error:(86, 21) error: cannot find symbol variable Uri
Error:(94, 22) error: cannot find symbol class ActivityNotFoundException
Error:(95, 62) error: cannot find symbol variable Uri
P.S: I am not an Android Developer
You should override shouldOverrideUrlLoading, determine if the url has the specified prefix, and then open the Whatsapp listing on Play Store, or if the Play Store is not installed, open it inside browser :
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
mPbar.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url) {
mPbar.setVisibility(View.GONE);
}
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("whatsapp://")) {
// create an intent for Play Store
final Uri uri = Uri.parse("market://details?id=com.whatsapp");
final Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
#SuppressWarnings({"NewApi", "deprecation"})
final int newDocumentFlag = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) ? Intent.FLAG_ACTIVITY_NEW_DOCUMENT : Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | newDocumentFlag | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
try {
// open Whatsapp listing in Play Store app
startActivity(goToMarket);
} catch (ActivityNotFoundException ex) {
// open Whatsapp listing in browser
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.whatsapp")));
}
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
});
EDIT
Add this lines to the top of the file to import the necessary classes :
import android.content.ActivityNotFoundException;
import android.net.Uri;

Android progressBar random crash with nullPointerException, can't understand why

Here's one of the tabs I have that loads a page.
package realstrat.cfostudio.magazineapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import realstrat.cfostudio.magazineapp.R;
public class TabActivity3 extends Activity {
WebView mWebView;
private ProgressDialog progressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.loadUrl("--company URL--");
mWebView.setWebViewClient(new FirstTabWebViewClient());
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean("OverviewMode", mWebView.getSettings().getLoadWithOverviewMode());
mWebView.saveState(savedInstanceState);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
((WebView)findViewById(R.id.webview1)).restoreState(savedInstanceState);
if (savedInstanceState.getBoolean("OverviewMode") == false) {
((WebView)findViewById(R.id.webpageview)).getSettings().setLoadWithOverviewMode(false);
((WebView)findViewById(R.id.webpageview)).getSettings().setUseWideViewPort(false);
}
else {
((WebView)findViewById(R.id.webpageview)).getSettings().setLoadWithOverviewMode(true);
((WebView)findViewById(R.id.webpageview)).getSettings().setUseWideViewPort(true);
}
return;
}
private class FirstTabWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// YouTube video link
if (url.startsWith("vnd.youtube"))
{
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return (true);
}
if (url.endsWith("-m.html")){
mWebView.getSettings().setLoadWithOverviewMode(false);
mWebView.getSettings().setUseWideViewPort(false);
}
else {
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
}
view.loadUrl(url);
return true;
}
public void onPageStarted(WebView view, String url, Bitmap favicon){
progressBar = ProgressDialog.show(TabActivity3.this, "", "Loading...", true);
}
public void onPageFinished(WebView view, String url) {
progressBar.hide();
if (url.endsWith("-m.html")){
mWebView.getSettings().setLoadWithOverviewMode(false);
mWebView.getSettings().setUseWideViewPort(false);
}
else {
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
}
return;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Context context = getApplicationContext();
CharSequence text = "Desc: " + description;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
return;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Once in a while it will crash with a nullPointerException on the line progressBar.hide() under onPageFinished(). That doesn't make any sense since onPageStarted() starts the progressBar, and onPageStarted always comes before onPageFinished(). Why is this?
This only happens like, once in 10 times or something, which is really confusing to me.
It usually happens (always?) when the activity is being started for the first time.
try this
if(progressBar!=null)
progressBar.hide();
Maybe the Activity has been restarted in between the two callbacks? Try rotating the phone while the progressBar is shown to see what the results are.
Try to load progress bar as singleton object. If you create anther progress bar object before hide first one then second progress bar will crash in hide().
if(_progressBar == null)
_progressBar = new ProgressDialog(this);

Categories

Resources