Adding ProgressBar into WebView Fragment - android

i'm finishing my app, is a simple app that contains some WebView Fragments and a Navigation Drawer, everything is OK, but I don't know how to add a progress bar while the WebView is loading a page, all I got is a blank screen before the page loads.
Here is my code...
HomeFragment.java
public class HomeFragment extends Fragment {
private WebView webView;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mainView = (View) inflater.inflate(R.layout.fragment_my_fragment1, container, false);
WebView webView = (WebView)mainView.findViewById(R.id.webview);
webView.setWebViewClient(new MantenerDominioWeb());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setSupportZoom(false);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setDomStorageEnabled(true);
webView.canGoBack();
webView.goBack();
webView.loadUrl("http://www.lfcchile.com/");
return mainView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
My WebViewClient class
public class MantenerDominioWeb extends WebViewClient {
private WebView webView;
public ProgressBar progressBarT4;
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().endsWith("lfcchile.com") || (Uri.parse(url).getHost().endsWith("thisisanfield.com")) || (Uri.parse(url).getHost().endsWith("liverpoolecho.co.uk")) || (Uri.parse(url).getHost().endsWith("liverpoolfc.com"))) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
And my Frame XML
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.lfcchile.MyFragment1">
<!-- TODO: Update blank fragment layout -->
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center"
android:text="#string/homefrag" />
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<ProgressBar
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:id="#+id/progressBar1"/>
</FrameLayout>
Any ideas please? I tried to put the progressBar "in front" of the WebView, but when the page is loaded the icon doesn't dissapear...

I believe it is not possible to put a progressbar because each site has a certain size, it would be difficult to measure it before finalizing the download page.
But you can place a pre-loader (loading) while the page is loaded and after the end you remove access for the user.
Use ProgressDialog:
public class HomeFragment extends Fragment {
private ProgressDialog progress;
private WebView webView;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mainView = (View) inflater.inflate(R.layout.fragment_my_fragment1, container, false);
WebView webView = (WebView)mainView.findViewById(R.id.webview);
webView.setWebViewClient(new MantenerDominioWeb());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setSupportZoom(false);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setDomStorageEnabled(true);
webView.canGoBack();
webView.goBack();
webView.loadUrl("http://www.lfcchile.com/");
progress = ProgressDialog.show(this, "Aguarde...",
"Processando sua solicitação.", true);
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
if (progress != null)
progress.dismiss();
}
});
return mainView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}

Set your ProgressBar to visibility="gone" to start
In your WebViewClient subclass, override onPageStarted() to set the visibility of the ProgressBar to VISIBLE
In your WebViewClient subclass, override onPageFinished() to set the visibility of the ProgressBar to GONE
Create a WebChromeClient subclass overriding onProgressChanged() to update the progress value of the ProgressBar
Add the WebChromeClient subclass to the WebView by calling WebView.setWebChromeClient()

Related

Store website cookies in Android Webview forever

I want to store my website cookies permanently in my Android Webview APk so that a user don't have to enter login details every time he starts the app. Please tell me in details as I am beginner. Any help will be appreciated.
This code will help you. Please take a look (you may copy/paste the code too)
public class MessangerMainFragment extends Fragment{
WebView telegram_web;
public MessangerMainFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
View v = inflater.inflate(R.layout.fragment_messanger_main, container, false);
setupUI(v);
init();
return v;
}
public void init() {
telegram_web.getSettings().setJavaScriptEnabled(true);
telegram_web.getSettings().setLoadWithOverviewMode(true);
telegram_web.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
telegram_web.getSettings().setUseWideViewPort(true);
telegram_web.getSettings().setDomStorageEnabled(true);
telegram_web.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, final String url) {
CookieSyncManager.getInstance().sync();
}
});
telegram_web.loadUrl("https://web.telegram.org/#/im");
}
public void setupUI(View v) {
telegram_web = v.findViewById(R.id.telegram_web);
if (!UniversalUtility.isOnline(getContext()))
UniversalUtility.handleFailureResponse("t.getMessage()", "messanger");
}
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CookieSyncManager.createInstance(getContext());
}
#Override
public void onResume() {
super.onResume();
CookieSyncManager.getInstance().startSync();
}
#Override
public void onPause() {
super.onPause();
CookieSyncManager.getInstance().stopSync();
}
#Override
public void onDetach() {
super.onDetach();
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
}

Webview doesn't take the full height

I am using Navigation Drawer with TabLayout. I have a fragment in which is WebView but the webview doesn't take in full height when running. I tried changing webview / relative layout height but didn't work . In the designer the height fits perfectly with the device on screen navigation buttons.
My xml code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/website_detail_1"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:indeterminate="false"/>
</RelativeLayout>
My Java Code
public class Tab1Fragment extends Fragment {
public WebView webView;
public ProgressBar progressBar;
public Tab1Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tab1, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
//
progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
// String url = "http://www.carsaleindiaofficial.com/?m=1";
webView = (WebView) view.findViewById(R.id.website_detail_1);
webView.setWebViewClient(new MyAppWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
//view.loadUrl(url);
webView.loadUrl("https://www.yahoo.com");
// view.loadUrl("file:///android_asset/web.html");
}
public class MyAppWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//view.findViewById(R.id.progressBar1).setVisibility(View.GONE);
Log.i("pageFinished", "yesss");
progressBar.setVisibility(View.INVISIBLE);
//progressBar.setVisibility(View.GONE);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
Result
The issue lay with viewpager height.
I believe you need to set the progress bar to VISIBILITY GONE.
INVISIBLE still reserves the space.
Try
<activity
android:name="YourActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="portrait">
</activity>

Non-static method 'onResume' Android Studio

I want to use a WebView for Youtube. When I try to compile it, I get this error "non-static method onResume & onPause cannot be referenced from a static context".
I have tried to use a rootView, but it didn't work ='(
public class vod extends Fragment {
public static final String TAG = "vod";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.vod, container, false);
WebView wv = (WebView)rootView.findViewById(R.id.webView2);
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
}
});
wv.setWebViewClient(
new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
wv.loadUrl("https://www.youtube.com/user/XX");
wv.addJavascriptInterface(new WebSocketFactory(wv), "WebSocketFactory");
return rootView;
}
#Override
public void onResume()
{
super.onResume();
WebView.onResume();
}
#Override
public void onPause()
{
super.onPause();
WebView.onPause();
}
}
I don't know how to resolve this. I need your help =)
Thank you =)
Make your wv variable as class member and use it then like this:
private WebView wv;
// onCreateView ...
#Override
public void onResume()
{
super.onResume();
wv.onResume();
}
And same with onPause...
You are trying to call the non-static methods onResume and onPause from WebView, but are accessing them in a static way. Either way, what you are doing makes no sense. Calling lifecycle methods manually is unnecessary and should be avoided. You can get rid of your onResume and onPause methods if you are only calling super.
If you want to call onResume and onPause from the Fragment, then use
wv.onResume and wv.onPause.
I modified your code below to solve your problem:
public class vod extends Fragment {
public static final String TAG = "vod";
private WebView wv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.vod, container, false);
wv = (WebView)rootView.findViewById(R.id.webView2);
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
}
});
wv.setWebViewClient(
new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
wv.loadUrl("https://www.youtube.com/user/XX");
wv.addJavascriptInterface(new WebSocketFactory(wv), "WebSocketFactory");
return rootView;
}
#Override
public void onResume()
{
super.onResume();
wv.onResume();
}
#Override
public void onPause()
{
super.onPause();
wv.onPause();
}
}
Also, class names should start with a capital letter, by convention. So call your Fragment Vod instead of vod.

Preventing WebView from closing when clicked outside the webview

In my app, I load a WebView where users enter username/password and I don't want the webview to close should the users accidentally click outside of the webview since the page will have to make another network call to load this webview.
I know this can be done for Dialog (like so: dialog.setCanceledOnTouchOutside(true);) but couldn't find similar mechanism for webview.
Thanks!
Here is the code:
#SuppressLint("SetJavaScriptEnabled")
public class LoginDialogFragment extends DialogFragment {
private static final String TAG = LoginDialogFragment.class.getSimpleName();
View mainView = null;
WebView webView = null;
OnLoginSucceeded loginSucceeded = null;
ProgressBar progressBar = null;
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.webview, container, false);
if (getDialog() != null)
getDialog().setTitle(getString(R.string.login));
webView = (WebView) mainView.findViewById(R.id.webview);
//display the progress bar
progressBar = (ProgressBar) mainView.findViewById(R.id.user_profile_loading_progress);
progressBar.setVisibility(View.VISIBLE);
//turn caching off
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginsEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
});
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.i(TAG, "URL received in onCreateView's onPageStarted is: " + url);
new HandleRequest().execute(url);
}
#Override
public void onPageFinished(WebView view, String url) {
}
});
new FetchLoginFormTask().execute();
return mainView;
}
I found my answer here and I just used getDialog().setCanceledOnTouchOutside(false); ensuring that when back key is clicked, the webview is dismissed.
Try with override the method:
#Override
public void setCancelable(boolean cancelable) {
super.setCancelable(false);
}
If your issue is not getting solved by this then please put some code so i can help you.
Feel free for comment.

Changing fragments and saving web view states - going mad

Ive been trying to do this for the best part of a week and still have no luck.
I have an action bar with tabs (action bar sherlock) and Im switching through the tabs and changing fragments fine.
Each fragment has a webview and Im trying to save the state of the webview so the web page stays on the same page that the user left it on.
Here is my fragment code:
public class FragmentB extends SherlockFragment {
WebView myWebView;
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
myWebView.saveState(outState);
Log.w("///////", "onSaveInstanceState");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
myWebView.restoreState(savedInstanceState);
Log.w("///////", "onActivityCreated");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.w("///////", "onCreate");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mainView = (View) inflater.inflate(R.layout.frag_b, container, false);
myWebView = (WebView) mainView.findViewById(R.id.webview);
Log.w("///////", "onCreateView");
if (savedInstanceState != null){
myWebView.restoreState(savedInstanceState);
Log.w("///////", "restore!");
}
else{
Log.w("///////", "ELSE!");
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.getSettings().setPluginsEnabled(true);
myWebView.getSettings().setBuiltInZoomControls(false);
myWebView.getSettings().setSupportZoom(false);
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.getSettings().setAllowFileAccess(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.loadUrl("http://www.google.com");
}
//return inflater.inflate(R.layout.frag_b, container, false);
return mainView;
}
public class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".mp4"))
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "video/*");
view.getContext().startActivity(intent);
return true;
}
else {
return super.shouldOverrideUrlLoading(view, url);
}
}
}
}
Any help would be great!
The onSaveInstanceState method of a fragment will only be called when the parent activity needs to save its state; an example of this is when the parent activity is being destroyed/recreated during an orientation change. As a result, this method won't be called when you are simply replacing fragments or switching between them as tabs.
As a workaround for your particular case, you can save the state of your webview in a bundle in the onPause method and restore it in the onActivityCreated method:
// Instance fields
private WebView webView;
private Bundle webViewBundle;
/**
* Save the state of the webview
*/
#Override
public void onPause()
{
super.onPause();
webViewBundle = new Bundle();
webView.saveState(webViewBundle);
}
/**
* Restore the state of the webview
*/
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
if (webViewBundle != null)
{
webView.restoreState(webViewBundle);
}
}
See here for more information as well:
How to save the state of a WebView inside a Fragment of an Action Bar

Categories

Resources