I programmed an app which opens a WebView via Imagebutton. If there is no Internet and the app is started a little popup comes up which says "No Internet". If i started the app with Internet and i lost the Internet during using the WebView a very ugly Screen shows up with error. How can i prevent my Webview loading a new side if there is no Internet, a small Toast should open or Textfield with "Sorry you lost your Connection :/", thanks!
Here my Code
public static boolean checkInternetConnection(Context context) {
ConnectivityManager con_manager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (con_manager.getActiveNetworkInfo() != null
&& con_manager.getActiveNetworkInfo().isAvailable()
&& con_manager.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
private ImageButton Ilias_link;
private ImageButton Lsf_link;
private WebView mWebView;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
if (!MainActivity.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "Du hast leider kein Internet", Toast.LENGTH_SHORT).show();
} else {
Ilias_link = (ImageButton) findViewById(R.id.ilias_link);
mWebView = new WebView(this);
Ilias_link.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(false);
mWebView.getSettings().setSupportZoom(true);
if (savedInstanceState == null)
mWebView.loadUrl("https://elearns02.fh-biberach.de/ilias3/login.php?target=&soap_pw=&ext_uid=&cookies=nocookies&client_id=HSBC&lang=de");
mWebView.setWebViewClient(new WebViewClient());
setContentView(mWebView);}
});
Lsf_link = (ImageButton) findViewById(R.id.lsf_link);
mWebView = new WebView(this);
Lsf_link.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(false);
mWebView.getSettings().setSupportZoom(true);
if (savedInstanceState == null)
mWebView.loadUrl("https://lsf.fh-biberach.de/qisserver/rds?state=user&type=0");
mWebView.setWebViewClient(new WebViewClient());
setContentView(mWebView);{
}};
})
;}
ImageButton imageButton = (ImageButton)findViewById((R.id.Mensaplan));
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Comming soon ;)",Toast.LENGTH_LONG).show();
}
});}
public void onPageFinished(WebView view, String url) {
String javascript="javascript:document.getElementsByName('viewport')[0].setAttribute('content', 'initial-scale=1.0,maximum-scale=10.0');";
view.loadUrl(javascript);
}
#Override
protected void onSaveInstanceState(Bundle outState )
{
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
mWebView.restoreState(savedInstanceState);
}
private static final int TIME_INTERVAL = 3000;
private long mBackPressed;
#Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
return;
} else
{ if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis())
{
super.onBackPressed();
return;
}
else { Toast.makeText(getBaseContext(), "Tap back button in order to exit", Toast.LENGTH_SHORT).show(); }
mBackPressed = System.currentTimeMillis();
}
}
}
Try doing this -
May be it will work. I made a project and used this.
DetectConnection.java
public class DetectConnection {
public static boolean checkInternetConnection(Context context) {
ConnectivityManager con_manager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (con_manager.getActiveNetworkInfo() != null
&& con_manager.getActiveNetworkInfo().isAvailable()
&& con_manager.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
}
The main code will be :-
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
} else {
wv = (WebView) findViewById(R.id.donate_webView1);
c = new CustomWebViewClient();
wv.setWebViewClient(c);
wv.clearCache(true);
wv.clearHistory();
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wv.getSettings().setBuiltInZoomControls(true);
wv.loadUrl("http://www.google.com");
}
// Function to load all URLs in same webview
private class CustomWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet!",Toast.LENGTH_SHORT).show();
} else {
view.loadUrl(url);
}
return true;
}
}
I hope it works :)
Related
I am trying to implement this loading future when implemented all the way the app will open it will show the loading circle but then will randomly turn the app off and exit with no error I'm unaware of why this keeps on happening or what exactly am I doing wrong I have listed my code for my main activity Java if someone could please help me that would be amazing.
public class MainActivity extends AppCompatActivity {
String ShowOrHideWebViewInitialUse = "show";
private ProgressBar spinner;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = findViewById(R.id.my_webview);
Button reloadBtn = findViewById(R.id.reload_btn);
ProgressBar progress = findViewById(R.id.my_progress);
TextView textView = findViewById(R.id.textView5);
WebSettings webSettings = webView.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setDisplayZoomControls(false);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
webView.setVisibility(View.GONE);
if (ShowOrHideWebViewInitialUse.equals("show")) {
webView.setVisibility(webView.INVISIBLE);
}
}
#Override
public void onPageFinished(WebView view, String url) {
ShowOrHideWebViewInitialUse = "hide";
spinner.setVisibility(View.GONE);
super.onPageFinished(view, url);
progress.setVisibility(View.GONE);
webView.setVisibility(View.VISIBLE);
}
});
if (isNetworkAvailable(this)) {
webView.loadUrl("https://racks.tk");
reloadBtn.setVisibility(View.GONE);
textView.setVisibility(View.GONE);
} else {
Toast.makeText(this, "No internet. Please check internet connection and try again", Toast.LENGTH_LONG).show();
reloadBtn.setVisibility(View.VISIBLE);
textView.setVisibility(View.VISIBLE);
}
reloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isNetworkAvailable(MainActivity.this)) {
reloadBtn.setVisibility(View.GONE);
textView.setVisibility(View.GONE);
webView.loadUrl("https://racks.tk");
} else {
reloadBtn.setVisibility(View.VISIBLE);
textView.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "No internet. Please check internet connection and try again", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
#SuppressLint("NonConstantResourceId")
#Override
public boolean onOptionsItemSelected(MenuItem item) {
WebView webView = findViewById(R.id.my_webview);
// Handle item selection
switch (item.getItemId()) {
case R.id.site:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://racks.tk")));
break;
case R.id.ribbon:
webView.reload();
break;
case R.id.support:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://racks.tk/support")));
break;
}
return false;
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
return capabilities != null && (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET));
} else {
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnected();
}
}
return false;
}
}
This is because you must receiving security exception as you are accessing network state.
Please add below permission in you manifest.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
In case you face any error and want to debug from android studio you can put "No Filter" instead "Show only selected application" sometime this works.
Your app is running successfully!
Hi I have totally no idea why my webview is not call the onPageFinished method, and the it was showing the loading dialog all the time, I hope there is someone out there help me for my this issue. In the Android manifest file I already put the internet permission and also the network access state.
so this is my code:
public class MainActivity extends AppCompatActivity {
WebView mWebView;
RelativeLayout rLoading;
Map<String, String> header;
String urlToLoad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webView);
rLoading = (RelativeLayout) findViewById(R.id.loading);
if ( isNetworkAvailable() == true ) //check if internet available or not
{
mWebView.setFocusable(true);
mWebView.setFocusableInTouchMode(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setDatabaseEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
urlToLoad = "https://www.google.com/";
UsernamePasswordCredentials creds= new UsernamePasswordCredentials("username", "password");
Header credHeader = BasicScheme.authenticate(creds, "UTF-8", true);
header = new HashMap<String, String>();
header.put(credHeader.getName(), credHeader.getValue());
//show loading dialog
mWebView.loadUrl(urlToLoad, header);
mWebView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url) {
rLoading.setVisibility(View.GONE);
}
});
}
else //Not connected
{
Toast.makeText(
this,
"No internet connection",
Toast.LENGTH_LONG
).show();
}
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivityMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityMgr.getActiveNetworkInfo();
/// if no network is available networkInfo will be null
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()){
mWebView.goBack();
}else {
super.onBackPressed();
}
}
}
Someone please help me
Try this Android WebView implementation:
webview= (WebView) findViewById(R.id.webview);
webview.loadUrl("www.google.com");
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//stop the ProgressBar
mProgressBar.setVisibility(View.INVISIBLE);
}
});
You can do it by this way
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap facIcon) {
//SHOW LOADING IF IT ISNT ALREADY VISIBLE
}
#Override
public void onPageFinished(WebView view, String url) {
progressDialog.dismiss();
}
});
Hi i've been searching a lot but couldn't find anything that could help.
I am creating an android app for our existing website. The website itself will load, but the main form where users can sign in won't load. Does anyone have any idea how this happens?
The website is https://app.one-2-ten.com/v2
p.s. This is the first time I am making an android app so sorry if its an obvious solution.
ProgressBar progressBar;
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
webView = (WebView) findViewById(R.id.webView);
if (savedInstanceState != null) {
webView.restoreState(savedInstanceState);
}
else{
webView.getSettings() .setJavaScriptEnabled(true);
webView.getSettings() .setSupportZoom(false);
webView.getSettings() .setBuiltInZoomControls(false);
webView.getSettings() .setLoadWithOverviewMode(true);
webView.getSettings() .setUseWideViewPort(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setWebViewClient(new ourViewClient());
webView.Settings.AllowContentAccess = true;
webView.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged (WebView view, int progress){
progressBar.setProgress(progress);
if(progress < 100 && progressBar.getVisibility() == ProgressBar.GONE){
progressBar.setVisibility(ProgressBar.VISIBLE);
}if(progress == 100){
progressBar.setVisibility(ProgressBar.GONE);
}
}
}
);}
String data = getIntent() .getDataString();
if(Intent.ACTION_VIEW.equals(getIntent() .getAction())){
webView.loadUrl(data);
}else{
webView.loadUrl("https://one2ten-system.parseapp.com/v2");
}
}
public class ourViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView v, String url) {
if (url.contains("one2ten-system.parseapp.com/v2")) {
v.loadUrl(url);
CookieManager.getInstance().setAcceptCookie(true);
} else {
Uri uri = Uri.parse(url);
startActivity(Intent.createChooser(new Intent(Intent.ACTION_VIEW, uri), "Choose browser"));
}
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
}
#Override
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
webView.saveState(outState);
}
}
I've found what my issue was, I forgot to add the following line: webView.getSettings().setDomStorageEnabled(true);
This enables the browser to store user data from forms for example, which it needs because you land on a login page.
If my answer is incomplete please let me know!
Thanks
im trying to make an webview application for android with progress bar, i tried a lot of examples from here but none was working .. my problem is that on a frame page or a page with facebook likes or comment plugin the progressdialog never stoped .. here is my code.. please test it and tell me what is wrong.
private WebView webview;
private ProgressDialog progressDialog;
boolean loadingFinished = true;
boolean redirect = false;
int nr = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.string.webview);
final Activity activity = this;
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
webview.loadUrl(url);
return true;
}
public void onLoadResource(WebView view, String url) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(activity);
progressDialog.setTitle("PitziWorld");
progressDialog.setMessage(progressDialog.toString());
progressDialog.setCancelable(isFinishing());
progressDialog.show();
}
loadingFinished = false;
}
public void onPageFinished(WebView view, String url) {
if(!redirect){
loadingFinished = true;
}
if(loadingFinished && !redirect){
if (progressDialog.isShowing() || progressDialog!=null) {
progressDialog.hide();
progressDialog = null;
}
} else{
redirect = false;
}
}
});
webview.loadUrl("http://www.pitziworld.ro");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
WebView webView = (WebView) findViewById(R.string.webview);
//Verifica daca tasta apasata a fost back si daca exista istoric
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
// Daca nu a fost tasta back sau nu este istoric, returnam valoare buton
`
this is what you are looking for!
public void onPageStarted(WebView view, String url, Bitmap favicon) {
mProgress.show();
}
to load progress bar in every page
this is it!
First code:
package com.fshare.zsee;
public class ZSEEActivity extends TabActivity {
private WebView webview ;
private WebView webviewtwo;
private TabHost mTabHost;
private WebSettings webviewtwoSettings;
private int error;
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
protected void onStop() {
super.onStop();
// The activity is about to become visible.
}
protected void onRestart() {
super.onRestart();
}
protected void onDestroy(){
super.onDestroy();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Activity activity = this;
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("Zastępstwa").setContent(R.id.tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("Plan Lekcji").setContent(R.id.tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("O programie").setContent(R.id.tab3));
webview = (WebView) findViewById(R.id.webView1);
webviewtwo = (WebView) findViewById(R.id.webView2);
webviewtwoSettings = webviewtwo.getSettings();
if (savedInstanceState != null){
error = savedInstanceState.getInt("webtwoerror");
webview.restoreState(savedInstanceState.getBundle("stateone"));
webviewtwo.restoreState(savedInstanceState.getBundle("statetwo"));
if(error == 1){
webviewtwoSettings.setTextSize(TextSize.NORMAL);
}
else{
webviewtwoSettings.setTextSize(TextSize.LARGER);
}
mTabHost.setCurrentTab(savedInstanceState.getInt("CURRENT_TAB"));
}
else{
webviewtwoSettings.setTextSize(TextSize.LARGER);
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
//error = 0 ;
mTabHost.setCurrentTab(0);
}
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webview.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
webviewtwo.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webviewtwoSettings.setTextSize(TextSize.NORMAL);
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webviewtwo.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
error = 1 ;
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
// put your stuff here or just block the back button for perticular activity
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);
}
return super.onKeyDown(keyCode, event);
}
protected void onSaveInstanceState(Bundle outState) {
Bundle outStateone = new Bundle();
Bundle outStatetwo = new Bundle();
webview.saveState(outStateone);
webviewtwo.saveState(outStatetwo);
outState.putBundle("stateone", outStateone);
outState.putBundle("statetwo", outStatetwo);
outState.putInt("CURRENT_TAB", mTabHost.getCurrentTab());
outState.putInt("webtwoerror", error);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.item1:
final AlertDialog alertdialog= new AlertDialog.Builder(this).create();
alertdialog.setTitle("O Programie");
alertdialog.setMessage("Zmiany w 1.0.1: \n-Obsługa planu z dnia 17.10.2011\n-Drobne Poprawki");
alertdialog.setButton("Fajno", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertdialog.cancel();
}
});
alertdialog.show();
return true;
case R.id.item2:
finish();
case R.id.item3:
if(mTabHost.getCurrentTab() == 0){
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
}
else if(mTabHost.getCurrentTab() == 1)
{
error = 0 ;
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
webviewtwoSettings.setTextSize(TextSize.LARGER);
}
default:
return super.onOptionsItemSelected(item);
}
}
}
And now very simple question. Why webviewtwo reload page after change orientation and webview (webView1) doesen't ? and how to prevent it? Now only webView1 doesen't reload page after change screen orientation.
Sierran
I am not sure why the first one doesn't change but adding this to my manifest inside of the activity tag worked for me
android:configChanges="orientation|keyboardHidden|keyboard"