Adding AdBlock to Layout Android - android

I'm new at android developing, so asking you for help.
I have the code like that:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout android:layout_width="fill_parent"
android:id="#+id/home_layout"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_above="#+id/adView">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="10dp"
android:id="#+id/progressBar" />
</LinearLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>
</LinearLayout>
In my logic, AdBlock should display at the bottom of view. But in my case it's just not appearing at all. If I past Ad's markup inside LinearLayout it gives me crash of VM.
What I'm doing wrong? Thank you in advance
UPD: Java activity
public class PddViewActivity extends ActionBarActivity{
private WebView webView;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pdd_view);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
String file = getIntent().getStringExtra("file");
webView = (WebView) findViewById(R.id.webview);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
Log.i("PROGRESS IS :", newProgress+"");
progressBar.setProgress(newProgress);
}
});
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Error: " + description + " " + failingUrl, Toast.LENGTH_LONG).show();
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
if (progressBar.getVisibility() == WebView.VISIBLE) {
progressBar.setVisibility(WebView.GONE);
}
}
});
webView.loadUrl(String.format("file:///android_asset/html/%s", file));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}

Your problem is that home_layout has a layoutHeight of match_parent, which means it will consume all the height of its parent leaving none for you adView.
Instead use wrap_content and specify android:layoutWeight="1" to tell it to consume all unused space. Eg
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/home_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="10dp"
android:id="#+id/progressBar" />
</LinearLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>
</LinearLayout>
Note also:
layout_above has no meaning except within a relative_layout.
fill_parent has been deprecated, use match_parent instead.
You had the same problem with your WebView.

Try with that in your PddViewActivity.java :
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
private WebView webView;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pdd_view);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//instaciate AdView
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
String file = getIntent().getStringExtra("file");
webView = (WebView) findViewById(R.id.webview);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
Log.i("PROGRESS IS :", newProgress+"");
progressBar.setProgress(newProgress);
}
});
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Error: " + description + " " + failingUrl, Toast.LENGTH_LONG).show();
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
if (progressBar.getVisibility() == WebView.VISIBLE) {
progressBar.setVisibility(WebView.GONE);
}
}
});
webView.loadUrl(String.format("file:///android_asset/html/%s", file));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}

Related

Add forward and back button on a custom toolbar

I am trying to add forward and back button on custom toolbar in android studio I have tried adding it as a menu as well as separate buttons but every time when I run the app the buttons are not appearing. Code is working fine I am not able to detect what am i missing here. Here is the code :
XML
<LinearLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/toolbar01"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="0dp"
android:layout_weight="0.4"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/menu_icon"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:src="#drawable/menu"
/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.3">
<Button
android:id="#+id/back"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/ic_baseline_arrow_back_ios_24">
</Button>
<Button
android:id="#+id/forward"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/ic_baseline_arrow_forward_ios_24">
</Button>
<Button
android:layout_marginLeft="50dp"
android:id="#+id/refresh"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/ic_baseline_refresh_24"
android:layout_marginStart="40dp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ProgressBar
android:id="#+id/pb"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:progress="50"
android:progressTint="#color/colorPrimary"
android:indeterminate="true"
android:indeterminateDuration="2000"
android:maxHeight="3dp"
android:minHeight="3dp"
tools:targetApi="lollipop" />
</LinearLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp"
>
<WebView
android:id="#+id/webView"
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp">
</WebView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</RelativeLayout>
</LinearLayout>
</androidx.drawerlayout.widget.DrawerLayout>
JAVA:
public class Webview extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private WebView webview;
NavigationView navigationView;
DrawerLayout drawer;
ImageView menuicon, forward, back, refresh;
static final float END_SCALE = 0.7f;
LinearLayout contentView;
ProgressBar progressBar;
SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
navigationDrawer();
Loadweb();
}
private void toolbuttons() {
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onForwardPressed();
}
});
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
webview.reload();
}
});
}
private void Loadweb() {
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
progressBar.setProgress(newProgress);
}
});
webview.setWebViewClient(new WebViewClient() {
#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);
swipeRefreshLayout.setRefreshing(false);
}
});
webview.loadUrl("https://www.nationalsavings.com.pk/index.php");
progressBar.setMax(100);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
webview.reload();
}
}, 3000);
}
});
swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
}
private void navigationDrawer() {
//navigation view
navigationView.bringToFront();
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_home);
menuicon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerVisible(GravityCompat.START))
drawer.closeDrawer(GravityCompat.START);
else drawer.openDrawer(GravityCompat.START);
}
});
animateNavigationDrawer();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.toolbar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.back:
onBackPressed();
break;
case R.id.forward:
onForwardPressed();
break;
case R.id.refresh:
webview.reload();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerVisible(GravityCompat.START) || webview.canGoBack()) {
drawer.closeDrawer(GravityCompat.START);
webview.goBack();
} else {
super.onBackPressed();
}
}
public void onForwardPressed() {
if (webview.canGoBack()) {
webview.goBack();
} else {
Toast.makeText(this, "Can't go back", Toast.LENGTH_SHORT).show();
}
}
private void animateNavigationDrawer() {
drawer.setScrimColor(getResources().getColor(R.color.colorPrimary));
//Add any color or remove it to use the default one!
//To make it transparent use Color.Transparent in side setScrimColor();
//drawerLayout.setScrimColor(Color.TRANSPARENT);
drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Scale the View based on current slide offset
final float diffScaledOffset = slideOffset * (1 - END_SCALE);
final float offsetScale = 1 - diffScaledOffset;
contentView.setScaleX(offsetScale);
contentView.setScaleY(offsetScale);
// Translate the View, accounting for the scaled width
final float xOffset = drawerView.getWidth() * slideOffset;
final float xOffsetDiff = contentView.getWidth() * diffScaledOffset / 2;
final float xTranslation = xOffset - xOffsetDiff;
contentView.setTranslationX(xTranslation);
}
});
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
// Handle the camera action
webview.loadUrl("https://www.nationalsavings.com.pk/index.php");
} else if (id == R.id.nav_privacy_policy) {
webview.loadUrl("https://www.nationalsavings.com.pk/privacy-policy.php");
} else if (id == R.id.nav_share) {
Intent shareintent = new Intent();
shareintent.setAction(Intent.ACTION_SEND);
shareintent.putExtra(Intent.EXTRA_TEXT, "https://www.nationalsavings.com.pk/index.php");
shareintent.setType("text/plain");
startActivity(Intent.createChooser(shareintent, "Share via"));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}

Opening a website in webview in a different fragment with a button

I have 2 buttons in different fragment1 and another webview in fragment 2. I want to open 2 different websites in the webview whenever I click on the buttons. Please suggest
Please try this -
public class MainHomeActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_first, btn_second;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_home);
btn_first= (Button)findViewById(R.id.btn_first);
btn_second= (Button)findViewById(R.id.btn_second);
btn_second.setOnClickListener(this);
btn_first.setOnClickListener(this);
}
private void loadFragment(String url) {
WebViewFragment webViewFragment = new WebViewFragment();
Bundle b = new Bundle();
b.putString("url", url);
webViewFragment.setArguments(b);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_layout, webViewFragment);
fragmentTransaction.commit();
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_first:
loadFragment("http://www.google.com");
break;
case R.id.btn_second:
loadFragment("http://www.apple.com");
break;
}
}
}
/activity_main_home.xml/
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/topPanel"
android:orientation="horizontal">
<Button
android:id="#+id/btn_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="first"/>
<Button
android:id="#+id/btn_second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="second"/>
</LinearLayout>
<FrameLayout
android:id="#+id/fragment_layout"
android:layout_below="#+id/topPanel"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</RelativeLayout>
//WebViewFragment.java
public class WebViewFragment extends Fragment {
private View view;
private WebView webview;
ProgressBar webViewPbar;
private String url ;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
url = bundle.getString("url");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_main, container, false);
initUI();
return view;
}
private void initUI() {
webViewPbar = (ProgressBar) view.findViewById(R.id.webViewPbar);
webview = (WebView) view.findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
webViewPbar.setProgress(newProgress);
if (newProgress == 100) {
webViewPbar.setVisibility(View.GONE);
}
}
});
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
if (webViewPbar != null) {
webViewPbar.setVisibility(View.GONE);
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (webViewPbar != null) {
webViewPbar.setVisibility(View.GONE);
}
}
});
// webview.loadUrl("http://www.google.com");
webview.loadUrl(url);
}
}
//activity_main.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">
<ProgressBar
android:id="#+id/webViewPbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
style="#android:style/Widget.Holo.Light.ProgressBar.Horizontal" />
<WebView android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
/androidmanifest file/
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.shajib.capturemirror">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
>
<activity android:name=".MainHomeActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

WebView and ProgressBar not appearing

So guys. I have a problem, I am creating an application and while the webview is charged, appears a ProgressBar loading before the content, see my code. The problem is that when you start the app, there is a white activity in place of the webview w the ProgressBar not appear. Follows the code.
<FrameLayout
android:id="#+id/framelayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webView"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:visibility="invisible"/>
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="invisible"/>
</FrameLayout>
</RelativeLayout>
NOW MY CLASS:
// CODE WebView
final WebView myWebView = (WebView) findViewById(R.id.webView);
myWebView.loadUrl("http://www.idestudos.com.br");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
myWebView.setWebViewClient(new MyBrowser());
myWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
myWebView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
ProgressBar pb = (ProgressBar) findViewById(R.id.progress);
pb.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url){
ProgressBar pb = (ProgressBar) findViewById(R.id.progress);
pb.setVisibility(View.INVISIBLE);
myWebView.setVisibility(View.VISIBLE);
}
});
}`
Your root FrameLayout has height set to 0dp, i.e., android:layout_height="0dp", but has weight set to 1, android:layout_weight="1", are you sure if its inside a LinearLayout? If not change the height to android:layout_height="match_parent" or something.
Also, you're setting the client twice.
myWebView.setWebViewClient(new WebViewClient() {...}); two times there in the code.
Do this instead.
myWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
ProgressBar pb = (ProgressBar) findViewById(R.id.progress);
pb.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url){
ProgressBar pb = (ProgressBar) findViewById(R.id.progress);
pb.setVisibility(View.INVISIBLE);
myWebView.setVisibility(View.VISIBLE);
}
});
Put the progressbar inside FrameLayout and FrameLayout below WebView so that the progressBar will stay on your screen even when you scroll through the WebView...
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="150dp">
<ProgressBar
<!-- your progress bar here-->
/>
</FrameLayout>
</RelativeLayout>

Progress bar and No internet connection in webview Fragment

I am trying to get a progress bar which shows until the web page is loaded. and if user has no internet connection than a text or toast is showed... but i am unable to get it worked.. searched the whole website. i think its easy to add progress bar to class that expends Activity...
here is my class and layout
package com.nirav.rpta.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import com.nirav.rpta.R;
public class OneFragment extends Fragment{
public OneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
WebView heroespage = (WebView) rootView.findViewById(R.id.webview);
WebSettings webSettings = heroespage.getSettings();
webSettings.setJavaScriptEnabled(true);
heroespage.loadUrl("http://google.co.in/");
return rootView;
}}
and my layout
<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="com.nirav.rpta.fragments.OneFragment">
<WebView
android:id="#+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
/></RelativeLayout>
Add a ProgressBar to your layout file:
<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="com.nirav.rpta.fragments.OneFragment">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:indeterminate="true"/>
</RelativeLayout>
Now in the code:
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
WebView heroespage = (WebView) rootView.findViewById(R.id.webview);
ProgressBar loading = (ProgressBar) rootView.findViewById(R.id.progress);
heroespage.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
loading.setVisibility(View.GONE);
heroespage.setVisibility(View.VISIBLE);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// Show error toast
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// Show error toast
}
});
heroespage.loadUrl("http://google.co.in/");
Please check below code for the thing you want.
Your layout
<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="com.nirav.rpta.fragments.OneFragment">
<WebView
android:id="#+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"/>
<ProgressBar
android:id="#+id/progressBar2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
Your Java file should be like below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
WebView heroespage = (WebView) rootView.findViewById(R.id.webview);
// Resources
progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar2);
WebSettings settings = heroespage.getSettings();
settings.setJavaScriptEnabled(true);
heroespage.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
// Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
}
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// Log.e(TAG, "Error: " + description);
Toast.makeText(WebViewScreen.this, "You are offline.",
Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.VISIBLE);
}
});
heroespage.loadUrl(URL);
return rootView;
}}
You must update your layout
<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="com.nirav.rpta.fragments.OneFragment">
<WebView
android:id="#+id/webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:id="#+id/progbar"/>
</RelativeLayout>
And then find id of progressbar ProgressBar prog = view.findViewById(R.id.progbar);
to check internet connection use this method
public boolean isConnectingToInternet( Context _context){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
add this code in your oncreateview
heroespage.setWebViewClient(new WebViewCLient(){
public void onPageLoadFinished(){
progbar.setvisibility(View.Gone);
});
if(isconnectingInternet(getActivity()){
heroespage.loadUrl("http://google.co.in/");
}else{
// show your toast here
}
to hide / show progress bar you can use setWebViewClient which provide onPage strated and onPageFinished method
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Show Progress bar
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// hide Progress bar
}
});
To check no internet connection , you can use below code
public static boolean isNetConnected() {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
} catch (Exception e) {
}
return false;
}
Use above method before loading url
if(isNetConnected()) {
heroespage.loadUrl("http://google.co.in/");
} else {
Toast.makeText(getActivity() ,"No internet connection",Toast.LENGTH_SHORT).show();
}

My progressbar in webview returns null and crashes?

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.

Categories

Resources