How to Load Cache Page in Webview - android

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

Related

can webview start an activity onReceivedError?

I am trying to start an activity (Errorpage) when webview failed to load content.But there is no error during the build, but the app closes, while inernet is off. It was supposed to launh the Errorpage activity.
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import androidx.appcompat.app.AppCompatActivity;
public class smwebview extends AppCompatActivity {
private WebView webview;
private ProgressBar spinner;
String ShowOrHideWebViewInitialUse = "show";
private WebView mWebView; //added for back buton override
public boolean mShouldPause = false;
String fullurl;
private ProgressBar spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smwebview);
getIntent();
fullurl= getIntent().getStringExtra("full_url");
webview = (WebView) findViewById(R.id.webView_Latest);
webview.setWebViewClient(new CustomWebViewClient());
spinner = (ProgressBar)findViewById(R.id.progressBar2);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setAppCacheEnabled(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// keep screen on
webview.loadUrl(fullurl);
private class CustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView webview, String url, Bitmap favicon) {
if (ShowOrHideWebViewInitialUse.equals("show")) {
webview.setVisibility(webview.INVISIBLE);
}
}
#Override
public void onLoadResource(WebView webview, String url) {
super.onLoadResource(webview, url);
if (url.contains("youtube.com")) mShouldPause = true;
}
public void onReceivedError(WebView webview, int errorCode, String description, String failingUrl) {
Intent intent7 = new Intent(smwebview.this,Errorpage.class);
startActivity(intent7);
}
#Override
public void onPageFinished(WebView view, String url) {
ShowOrHideWebViewInitialUse = "hide";
spinner.setVisibility(View.GONE);
view.setVisibility(webview.VISIBLE);
super.onPageFinished(view, url);
}
}
public class WebViewClient extends android.webkit.WebViewClient {
#Override
public void onPageStarted(WebView webview, String url, Bitmap favicon) {
if (ShowOrHideWebViewInitialUse.equals("show")) {
webview.setVisibility(webview.INVISIBLE);
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
ShowOrHideWebViewInitialUse = "hide";
spinner.setVisibility(View.GONE);
view.setVisibility(webview.VISIBLE);
super.onPageFinished(view, url);
}
}
#Override
public void onResume()
{
super.onResume();
webview.onResume();
}
#Override
public void onPause() {
super.onPause();
if(mShouldPause){
webview.onPause();
}
mShouldPause = false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webview.canGoBack()) {
webview.goBack();
} else {
super.onBackPressed();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
If anybody have any idea Please help me. Also please comment your suggestions on the code/logic. (I am very new to android programming)
Internet if off. Its different scenario you must add check internet connection before load.
Or onRwleceiveError is different case. When you load wrong url or utl you entered is not working

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().

WebView not loading url in Android 4.4+

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.

Redirect to main activity after login

I want to redirect to my main activity after login.
when I put this code I get this error:
The method parseObssoCookie(String, String) is undefined for the type LoginActivity.Callback LoginActivity.java
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class LoginActivity extends Activity {
private WebView webView;
LoginActivity webActivity;
public static String loginCookie = null;
private static CookieManager cookieManager;
ProgressDialog progDailog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
webActivity = this;
webView = (WebView) findViewById(R.id.LoginWebView);
progDailog = ProgressDialog.show(this, "Loading Application",
"please wait while page is loading..", true);
// use cookies to remember a logged in status
cookieManager = CookieManager.getInstance();
cookieManager.setCookie("set-cookie",null);
cookieManager.removeAllCookie();
cookieManager.setAcceptCookie(true);
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
String url = "https://www.example.com/login.aspx"; //the web url
loginCookie = cookieManager.getCookie(url);
String obsso = parseObssoCookie(url, "ObSSOCookie");
if ((loginCookie != null) && (obsso != null)
&& (!"loggedoutcontinue".equalsIgnoreCase(obsso))) {
finish();
Intent intent = new Intent(this, ActivityMainTabHolder.class);
startActivity(intent);
} else {
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.setWebViewClient(new Callback());
webView.loadUrl(url);
}
}
private class Callback extends WebViewClient {
#override
public void onpagestarted(webview view, string url, bitmap favicon) {
// todo auto-generated method stub
progdailog.dismiss();
super.onpagestarted(view, url, favicon);
}
#override
public boolean shouldoverrideurlloading(webview view, string url) {
return super.shouldoverrideurlloading(view, url);
}
#override
public void onpagefinished(webview view, string url) {
// todo auto-generated method stub
super.onpagefinished(view, url);
logincookie = cookiemanager.getinstance().getcookie(url);
if (logincookie != null) {
string obsso = parseobssocookie(url, "obssocookie");
if ((obsso != null)
&& !("loggedoutcontinue".equalsignorecase(obsso))) {
finish();
intent intent = new intent(webactivity, activitymaintabholder.class);
startactivity(intent);
}
}
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
cookieManager = CookieManager.getInstance();
cookieManager.setCookie("set-cookie",null);
cookieManager.removeAllCookie();
cookieManager.setAcceptCookie(true);
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
super.onResume();
}
}
Edit:
#Deepak : I did what you said but still it's not redirecting me to ActivityyMainTabHolder.class.
See my code below:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class LoginActivity extends Activity {
private WebView webView;
LoginActivity webActivity;
public static String loginCookie = null;
private static CookieManager cookieManager;
ProgressDialog progDailog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
webActivity = this;
webView = (WebView) findViewById(R.id.LoginWebView);
progDailog = ProgressDialog.show(this, "Loading Application",
"please wait while page is loading..", true);
// use cookies to remember a logged in status
cookieManager = CookieManager.getInstance();
cookieManager.setCookie("set-cookie",null);
cookieManager.removeAllCookie();
cookieManager.setAcceptCookie(true);
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
String url = "https://www.example.com/login.aspx"; //the web url
loginCookie = cookieManager.getCookie(url);
String obsso = parseObssoCookie(url, "ObSSOCookie");
if ((loginCookie != null) && (obsso != null)
&& (!"loggedoutcontinue".equalsIgnoreCase(obsso))) {
Intent intent = new Intent(webActivity, ActivityMainTabHolder.class);
startActivity(intent);
finish();
} else {
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.setWebViewClient(new Callback());
webView.loadUrl(url);
}
}
private String parseObssoCookie(String url, String string) {
// TODO Auto-generated method stub
return null;
}
private class Callback extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
progDailog.dismiss();
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
loginCookie = CookieManager.getInstance().getCookie(url);
if (loginCookie != null) {
String obsso = parseObssoCookie(url, "ObSSOCookie");
if ((obsso != null)
&& !("loggedoutcontinue".equalsIgnoreCase(obsso))) {
Intent intent = new Intent(webActivity, ActivityMainTabHolder.class);
startActivity(intent);
finish();
}
}
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
cookieManager = CookieManager.getInstance();
cookieManager.setCookie("set-cookie",null);
cookieManager.removeAllCookie();
cookieManager.setAcceptCookie(true);
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
super.onResume();
}
}
finish();
Intent intent = new Intent(this, ActivityMainTabHolder.class);
startActivity(intent);
replace with
Intent intent = new Intent(LoginActivity.this, ActivityMainTabHolder.class);
startActivity(intent);
finish();
You need to create your method parseObssoCookie(...)
you need to create parseObssoCookie(String, String) method as public in LoginActivity.java class
finish();
intent intent = new intent(webactivity, activitymaintabholder.class);
startactivity(intent);
replace with
Intent intent = new Intent(webactivity, ActivityMainTabHolder.class);
startActivity(intent);
finish();

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