I have written sample webview code by looking at examples found from internet. I want to show progressbar till webview loads a page in my fragment.
My activity contains toolbar, frame that shows fragments and navigation drawer. When i select an entry from navigation drawer, new fragment is shown which contains progress bar and webview and the fragment simply tries to load the page below is the code for fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_full_page, container, false);
//int view_num = getArguments().getInt(ARG_SECTION_NUMBER);
progressBar = (ProgressBar)rootView.findViewById(R.id.webviewProgress);
progressBar.setVisibility(View.VISIBLE);
webView = (WebView) rootView.findViewById(R.id.webView1);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setAppCacheEnabled( true );
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(true);
//webView.getSettings().setSupportZoom(true);
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
String urlString = getArguments().getString("URLSTRING");
final Boolean clickable = getArguments().getBoolean("CLICKABLE");
Boolean networkAvailable = Utils.isNetworkAvailable(super.getActivity().getApplicationContext());
if(networkAvailable == true) {
webView.loadUrl(urlString);
} else {
webView.loadUrl(Utils.DEFAULT_URL_PAGE);
}
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//progressBar.setVisibility(View.VISIBLE);
if (clickable) {
view.loadUrl(url);
return false;
} else {
return true;
}
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
});
webView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return rootView;
}
Below is fragment_full_page.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=".FragmentFullPage" >
<ProgressBar
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center|top"
android:id="#+id/webviewProgress"
/>
<WebView
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
web page is taking time to load (tried with wifi and 3g) but progress bar is not showing any time.
To test if progressbar actually shows in the middle of the fragment_full_page, I removed webview code and just kept progress bar then it is showing.
made something wrong with the code that is not showing progress bar while webview is loading which i am unable to figure out.
Related
Anyone can take a look at my code and let me know what I am missing?
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
mWebView.loadUrl("https://yahoo.com");
return true;
case R.id.navigation_dashboard:
mWebView.loadUrl("https://google.com");
return true;
case R.id.navigation_notifications:
mWebView.loadUrl("https://apple.com");
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
mWebView = (WebView) findViewById(R.id.webkit);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
WebSettings webSettings = mWebView.getSettings();
webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
webSettings.setDomStorageEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
mWebView.loadUrl("https://google.com");
return true;
}
});
}
}
activity_main.xml (layout file):
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webkit"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
My code is at: https://github.com/tlkahn/neonx
If you think this is too vague or off-topic, please comment and I will close it.
Replace
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
mWebView.loadUrl("https://google.com");
return true;
}
});
With
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return false;
}
});
Give the host application a chance to take control when a URL is about
to be loaded in the current WebView. If a WebViewClient is not
provided, by default WebView will ask Activity Manager to choose the
proper handler for the URL. If a WebViewClient is provided, returning
true causes the current WebView to abort loading the URL, while
returning false causes the WebView to continue loading the URL as
usual.
So far from what I can tell you are supposed to extend the WebViewClient class with a separate class:
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
and then set it to the WebViewClient:
mWebView.setWebViewClient(new MyBrowser());
Also try adding settings for loading images automatically, enabling javascript and setting scrollbar:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
mWebView.getSettings().setLoadsImagesAutomatically(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
case R.id.navigation_home:
mWebView.loadUrl("https://yahoo.com");
return true;
case R.id.navigation_dashboard:
mWebView.loadUrl("https://google.com");
return true;
case R.id.navigation_notifications:
mWebView.loadUrl("https://apple.com");
return true;
}
return false;
}
if you are using android 8+ then you must have to do 2 things.
Add this android:usesCleartextTraffic="true" attribute in manifest application tag. AndroidManifest.xml
you should override this method.
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.load(request.getUrl().toString())
return true;
}
});
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
mWebView.loadUrl("https://facebook.com");
return true;
}
});
Very good at all.
I have a fragment is called a drawerlist. Within this fragment I have a webView showing a web page.
I can surf the web, but the problem comes when I want to return to the previous page, and pulse on the back button.
The result I get is that pressing the back button, the application closes. And what I want is to return to the previous page.
Code fragment is as follows:
public class BClasesWebViewFragment extends Fragment {
private WebView webView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
WebSettings webSettings = this.webView.getSettings ();
webSettings . setJavaScriptEnabled ( true );
webSettings . setDomStorageEnabled ( true );
this . webView . setWebViewClient ( new WebViewClient ());
this . webView . setWebChromeClient ( new WebChromeClient ());
webSettings . setLoadWithOverviewMode ( true );
webSettings . setUseWideViewPort ( true );
webView.setInitialScale(1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl("http://google.com/");
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_bclases_webview, container, false);
webView = (WebView)view.findViewById(R.id.webViewBClases);
return view;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.actionbar_menu, menu);
super.onCreateOptionsMenu(menu,inflater);
}
}
Thank you very much everyone.
I learned a lot on this site
Try this
webView.setOnKeyListener(new OnKeyListener()
{
#Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
this will work perfectly.
I am trying to add a progressbar to a webview class.However, even after following all steps correctly, it crashes with a null pointer exception, any idea why?
Here's my mainactivity:
public class MainActivity extends Activity {
WebView webview;
ProgressBar progress;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// getWindow().requestFeature(Window.FEATURE_PROGRESS);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
webview = (WebView)findViewById(R.id.webview);
webview.setInitialScale(1);
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
progress = (ProgressBar) webview.findViewById(R.id.ProgressBar);
progress.setVisibility(View.VISIBLE);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
// webview.setWebViewClient(new MyCustomWebViewClient());
webview.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
webview.setScrollbarFadingEnabled(false);
webview.getSettings().setRenderPriority(RenderPriority.HIGH);
webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
// webview.getSettings().setBlockNetworkLoads(true);
webview.getSettings().setBuiltInZoomControls(true);
webview.loadUrl("http://www.yahoo.com");
webview.getSettings().setSupportZoom(false);
/* webview.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view, int progress)
{
// update the progressBar
MainActivity.this.setProgress(progress * 100);
}
});*/
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack() == true){
webview.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progress.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url) {
progress.setVisibility(View.GONE);
}
}
}
and here's the corresponding xml:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity" >
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<ProgressBar
android:id="#+id/ProgressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:maxHeight="30dp"
android:minHeight="30dp" />
</RelativeLayout>
Change
progress = (ProgressBar) webview.findViewById(R.id.ProgressBar);
to
progress = (ProgressBar)findViewById(R.id.ProgressBar);
Progressbar belongs to main.xml. findViewById looks for a view in the current inflated layout. You have set the content of layout main.xml to your activity.
I see that you copied an example, but you did it wrong. Replace the commented code with this:
webView.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view, int prog)
{
progress.setProgress(prog * 100);
}
});
Also, as said in the other post, that webview in webview.findViewById needs to be removed.
Hello i have a weird thing here, i have a list of items and i want when i click on any item, it will open an WebView which looks like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:theme="#android:style/Theme.Dialog">
<WebView android:id="#+id/BrowserView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY" />
here is the code i invoke the WebView
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
setContentView(R.layout.external_view);
// load url or html
RssItem listItem = (RssItem) listView.getItemAtPosition(position);
webView = (WebView) findViewById(R.id.BrowserView);
// set browser settings
webView.setWebViewClient(new ExternalWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
webView.setInitialScale(1);
try {
webView.loadUrl(listItem.getExternalUrl());
} catch (Exception ex) {
Log.d("WEBVIEW", ex.getMessage());
}
}
});
Here is the "ExternalWebViewClient" class
public class ExternalWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
view.clearHistory();
}
}
Now the question:
How do i close it and stay in the same activity after i press the "back" button,
here is my back button handling code:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack() == true) {
webView.goBack();
} else {
//what should i do here?????????????????
return true;
}
}
}
return false;
}
Basically, you should not need to handle Back button yourself. If you are in the WebView and press Back - you should be taken to your last activity by default.
The Program keeps crashing when i try to run it on my handset. cant figure out why it is crashing
Main java
public class ProgressBar extends Activity {
WebView webview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main );
final Activity MyActivity = this;
// Makes Progress bar Visible
getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
webview = (WebView) findViewById(R.id.webview);
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
//Make the bar disappear after URL is loaded, and changes string to Loading...
MyActivity.setTitle("Loading...");
MyActivity.setProgress(progress * 100); //Make the bar disappear after URL is loaded
// Return the app name after finish loading
if(progress == 100)
MyActivity.setTitle(R.string.app_name);
}
});
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.google.com/");
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
</LinearLayout>
You'll want to find the stacktrace from the crash, you can get this with logcat, either open the logcat view in eclipse (or open the DDMS perspective), or run adb logcat from the shell to see the log.
In this case though, i'm pretty sure you'll see any error saying you need to set the window feature before creating any content, move your setContentView call to after the getWindow().requestFeature call.