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

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

Related

My Webview in fragment always refresh when i switch my tab from one to other

I want to save instant of my fragment and then restore back on reopening the tab. when switching from one tab to other.
here is my fragment code:
package com.mhm.universityofwah.fragments;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.mhm.universityofwah.R;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
import jp.co.recruit_lifestyle.android.widget.WaveSwipeRefreshLayout;
public class WebFragment extends Fragment implements WaveSwipeRefreshLayout.OnRefreshListener {
private WaveSwipeRefreshLayout swipeRefreshLayout;
private WebView mWebView;
private Activity context;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setRetainInstance(true);
View view = inflater.inflate(R.layout.fragment_avicenna, container, false);
mWebView = (WebView) view.findViewById(R.id.webview);
swipeRefreshLayout = (WaveSwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
swipeRefreshLayout.setOnRefreshListener((WaveSwipeRefreshLayout.OnRefreshListener) WebFragment.this);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
swipeRefreshLayout.setRefreshing(true);
}
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
}
});
BottomNavigationView bottomNavigationView=view.findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListner);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(false);
mWebView.setWebViewClient(new Callback());
if(savedInstanceState==null){
loadWebsite();
}
return view;
}
private BottomNavigationView.OnNavigationItemSelectedListener navListner=
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_refresh:
mWebView.reload();
break;
case R.id.nav_back:
if(mWebView.canGoBack()){
mWebView.goBack();
}
break;
case R.id.nav_forward:
if(mWebView.canGoForward()){
mWebView.goForward();
}
break;
}
return true;
}
};
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void loadWebsite() {
ConnectivityManager cm = (ConnectivityManager) Objects.requireNonNull(getActivity()).getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
mWebView.loadUrl("http://uow.edu.pk");
} else {
Toast.makeText(Objects.requireNonNull(getActivity()).getApplicationContext(), "Please Check Network Connection!", Toast.LENGTH_SHORT).show();
swipeRefreshLayout.setRefreshing(false);
}
}
public class Callback extends WebViewClient {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(Objects.requireNonNull(getActivity()).getApplicationContext(), "Please Check Network Connection!", Toast.LENGTH_SHORT).show();
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".pdf")) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}else if (url.contains("mailto:")) {
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}else if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
return true;
}else {
view.loadUrl(url);
return true;
}
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
swipeRefreshLayout.setRefreshing(true);
}
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
}
}
#Override
public void onRefresh() {
mWebView.reload();
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
}
}
#Override
public void onSaveInstanceState(#NotNull Bundle outState )
{
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public boolean onKey(View v, int keyCode, KeyEvent event ) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
Objects.requireNonNull(getActivity()).finish();
}
return true;
}
}
// here your code
return false;
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
this.context = (Activity) context;
}
}
I have 4 tabs but when i switch from one tab to other and come back to first one, it always reload. i tried every thing but my problem is not solved. Please help me to get this thing done.
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setRetainInstance(true);
if(view == null){
view = inflater.inflate(R.layout.fragment_avicenna, container, false);
mWebView = (WebView) view.findViewById(R.id.webview);
swipeRefreshLayout = (WaveSwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
swipeRefreshLayout.setOnRefreshListener((WaveSwipeRefreshLayout.OnRefreshListener) WebFragment.this);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
swipeRefreshLayout.setRefreshing(true);
}
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
}
});
BottomNavigationView bottomNavigationView=view.findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListner);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(false);
mWebView.setWebViewClient(new Callback());
if(savedInstanceState==null){
loadWebsite();
}
}
return view;
}
please make view a global variable and add null check when your onCreate view recalls it recreates the view so add check that if view != null then only return already initialized view instead of creating again

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 android app not loading any image or navigate in the website link

I am trying to load the site in an android app web view.
The site loads without the images ,all the images from the site are not loaded and i can't add to the cart product or even open details of other product
The code for MainActivity.java is shown below.
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://shopliek.com");
mWebView.setWebViewClient(new MyAppWebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
}});
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/** Inflating the current activity's menu with res/menu/items.xml */
getMenuInflater().inflate(R.menu.menu_main, menu);
/** Getting the actionprovider associated with the menu item whose id is share */
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
/** Setting a share intent */
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return super.onCreateOptionsMenu(menu);
}
/** Returns a share intent */
private Intent getDefaultShareIntent(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Make your Life Easier");
intent.putExtra(Intent.EXTRA_TEXT," Visit google");
return intent;
}
}
and also this MyAppWebViewClient:
public class MyAppWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("www.shopliek.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
I'm beginner so please explain kindly with simple instruction and thanks
Try this
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.google.com");
Hope this will work. Let me know if it works.
I've used the below code & everything worked correctly: show pictures, details page ... ...
public class WebviewActivity extends Activity {
#BindView(R.id.webview)
WebView web;
#BindView(R.id.progressBar)
ProgressBar progressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
ButterKnife.bind(this);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(WebserviceUrl.BASE_URL);
} catch (Exception e) {
e.printStackTrace();
}
}
public class myWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
progressBar.setVisibility(View.VISIBLE);
web.loadUrl(url);
return true;
}
public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
final AlertDialog.Builder builder = new AlertDialog.Builder(WebviewActivity.this);
builder.setMessage(R.string.notification_error_ssl_cert_invalid);
builder.setPositiveButton(R.string.continue_to_page, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.proceed();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.cancel();
}
});
final AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
}
try it & let me know the result

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