i have back button in my webview and its linked with loading screen (when i click back button its show loading animation (its named progressBar in the code).
But i have problem when i make fast few clicks my loading screen is looping.
Its any way to make the back button work only one time on page?
Like 1 click = 1 action, no more and stack.
For example i click on the back button, and its off for next click, but when page reloaded button work again.
Button przycisk_powrot = (Button) findViewById(R.id.przycisk_powrot);
przycisk_powrot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mywebView.goBack();
progressBar.setVisibility(View.VISIBLE);
}
});
Button przycisk_powrot = (Button) findViewById(R.id.przycisk_powrot);
przycisk_powrot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mywebView.goBack();
progressBar.setVisibility(View.VISIBLE);
}
});
#Override
public void onBackPressed(){
if(mywebView.canGoBack()) {
mywebView.goBack();
}
else{
super.onBackPressed();
}
}
public class WebViewClient extends android.webkit.WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.GONE);
}
}, 1000);
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean overrideUrlLoading = false;
progressBar.setVisibility(View.VISIBLE);
view.loadUrl(url);
return true;
}
Related
I have an activity containing a WebView and ProgressBar. During the loading of a web page, the progress bar appears and gradually horizontally fills. How can the visibility of the progress bar be set to View.GONE after the animation has finished?
public class WebviewActivity extends AppCompatActivity {
WebView myWebView;
ProgressBar pBar;
ProgressBar myProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_webview);
}
#Override
protected void onStart() {
super.onStart();
setContentView(R.layout.fragment_webview);
myProgressBar = findViewById(R.id.mProgressBar);
myProgressBar.setMax(100);
String url = getIntent().getStringExtra("url");
myWebView = findViewById(R.id.webview01);
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl(url);
myWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
myProgressBar.setProgress(newProgress);
if (newProgress == 100) {
AlphaAnimation fadeOut;
fadeOut = new AlphaAnimation(1,0);
fadeOut.setDuration(500);
fadeOut.setFillAfter(true);
myProgressBar.startAnimation(fadeOut);
// myProgressBar.setVisibility(View.GONE);
} else {
myProgressBar.setVisibility(View.VISIBLE);
}
}
});
}
private class WebViewClient extends android.webkit.WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request){
String url=request.getUrl().toString();
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// myProgressBar.setVisibility(View.GONE);
}
}
}
Use a listener:
fadeOut.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {}
#Override
public void onAnimationRepeat(Animation animation) {}
#Override
public void onAnimantionEnd(Animation animation) {
myProgressBar.setVisibility(View.GONE);
}
});
Try setting an animation listener to the animation object (fadeOut):
myWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
myProgressBar.setProgress(newProgress);
if (newProgress == 100) {
AlphaAnimation fadeOut;
fadeOut = new AlphaAnimation(1, 0);
fadeOut.setDuration(500);
fadeOut.setFillAfter(true);
fadeOut.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
// whatever you want to happen when the fadeOut animation starts
}
#Override
public void onAnimationEnd(Animation animation) {
// whatever you want to happen when the fadeOut animation ends
myProgressBar.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation animation) {
// whatever you want to happen when the fadeOut animation repeats itself
}
});
myProgressBar.startAnimation(fadeOut);
} else {
myProgressBar.setVisibility(View.VISIBLE);
}
}
});
With the callbacks above, you can hook into AnimationStart, AnimationEnd and AnimationRepeat.
Progress Dialog Does Not Dismiss After Loading Webview Is Goes On loading After Webview Is Loaded.
public class MainActivity extends AppCompatActivity {
private WebView webView;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pd = ProgressDialog.show(MainActivity.this, "Progress Dialog", "Loading...");
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new myWebClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://kkgupta.mmiswebtech.com");
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
try {
webView.stopLoading();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("file:///android_asset/error.html");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(webView, errorCode, description, failingUrl);
}
});
}
class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
// This method is used to detect back button
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}
You'll need to add onPageFinished() to your MyWebClient and in it call dismiss() on your ProgressDialog:
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
pd.dismiss();
}
use
pd.dismiss();
where u want ti dismiss Dialog.
Note: ProgressDialog is deprecated in API level 26. Better Use ProgressBar
Delete this code:
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
try {
webView.stopLoading();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("file:///android_asset/error.html");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(webView, errorCode, description, failingUrl);
}
});
}
change:
class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
To:
class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (pd.isShowing()) { pd.dismiss(); } }
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
I am new to android development, I have tried to override onBackPress() to implement webView.GoBack(). But on pressing back key my apps getting crashed. Here is my MainActivity.java code. Am I doing something wrong ??
public class MainActivity extends AppCompatActivity {
private WebView webview;
/** Called when the activity is first created. */
public void onBackPressed (){
if (webview.isFocused() && webview.canGoBack()) {
webview.goBack();
}
else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView view = (WebView) findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyCustomWebViewClient());
view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
view.loadUrl("http://url");
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.imageLoading1).setVisibility(View.GONE);
//show webview
findViewById(R.id.webView).setVisibility(View.VISIBLE);
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (view.canGoBack()) {
view.goBack();
} else {
view.loadUrl("file:///android_asset/index.html");
}
Toast.makeText(getBaseContext(), description, Toast.LENGTH_LONG).show();
}
}
}
Just because your webView is null. You are not referencing it anywhere. Modified your code.
public class MainActivity extends AppCompatActivity {
private WebView view;
/** Called when the activity is first created. */
public void onBackPressed (){
if (view.isFocused() && view.canGoBack()) {
view.goBack();
}
else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (WebView) findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyCustomWebViewClient());
view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
view.loadUrl("http://url");
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.imageLoading1).setVisibility(View.GONE);
//show webview
findViewById(R.id.webView).setVisibility(View.VISIBLE);
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (view.canGoBack()) {
view.goBack();
} else {
view.loadUrl("file:///android_asset/index.html");
}
Toast.makeText(getBaseContext(), description, Toast.LENGTH_LONG).show();
}
}
}
In onCreate you have:
WebView view = (WebView) findViewById(R.id.webView);
The WebView you have defined at the top has not been initialized, and is the one being used by the onBackPressed method, to fix this all you need to do is remove WebView before initializing the variable in onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (WebView) findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyCustomWebViewClient());
view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
view.loadUrl("http://url");
}
Actually you can not do directly inside the fragment. The onBackPressed can be overridden in the FragmentActivity. What you can do is:
1.Override the onBackPressed inside the activity.
2.When the onBackPressed is called, check if the instance of the current fragment is the instance showing the webview.
3.If it is, ask the fragment if the webview can go back.
4.If it is not, call the super or whatever you need
#Override
public void onBackPressed() {
Fragment webview = getSupportFragmentManager().findFragmentByTag("webview");
if (webview instanceof MyWebViewFragment) {
boolean goback = ((MyWebViewFragment)webview).canGoBack();
if (!goback)
super.onBackPressed();
}
}
I'm loading data in a webview using loadDataWithBaseURL from a string. I want to implement a listener which tells me when the data is loaded completely so that i may proceed with my code.
I've searched a lot but could not find any relevant topic
if (new String(rowData.getResource().getData()) != null) webView.loadDataWithBaseURL("", new String(rowData.getResource().getData()), "text/html", "UTF-8", "about:blank");
Use WebViewClient and implement onPageStarted,onPageFinished to know the status of the webview.
ProgressDialog progressDialog = new ProgressDialog.show(this);
progressDialog.setMessage("Loading WebPage...");
class CustomWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressDialog.dismiss();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressDialog.show();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
}
webview.setWebViewClient(new CustomWebViewClient());
Try this Tested working demo.
public class URLActivity extends Activity {
private ProgressDialog progress;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
WebView webView = (WebView) findViewById(R.id.webView);
webView.setInitialScale(0);
webView.setWebViewClient(new WebViewClient());
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setLoadsImagesAutomatically(true);
webView.loadDataWithBaseURL("", new String(rowData.getResource().getData()), "text/html", "UTF-8", "about:blank");
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
if (newProgress > 0) {
showProgressDialog("Please Wait");
}
if (newProgress >= 100) {
hideProgressDialog();
// data load successfully. you can go further.
}
}
});
}
public void showProgressDialog(final String msg) {
runOnUiThread(new Runnable() {
public void run() {
if (progress == null || !progress.isShowing()) {
progress = ProgressDialog.show(URLActivity.this, "", msg);
}
}
});
}
public void hideProgressDialog() {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
if (progress.isShowing())
progress.dismiss();
} catch (Throwable e) {
}
}
});
}
}
Simple code:
public class ZSEEActivity extends TabActivity {
private WebView webview ;
private WebView webviewtwo;
private TabHost mTabHost;
private int a;
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);
final WebSettings webviewtwoSettings = webviewtwo.getSettings();
if (savedInstanceState != null){
webview.restoreState(savedInstanceState.getBundle("stateone"));
webviewtwo.restoreState(savedInstanceState.getBundle("statetwo"));
webviewtwoSettings.setTextSize(TextSize.LARGER);
mTabHost.setCurrentTab(savedInstanceState.getInt("CURRENT_TAB"));
}
else{
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
webviewtwoSettings.setTextSize(TextSize.LARGER);
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) {
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");
webviewtwoSettings.setTextSize(TextSize.NORMAL);
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
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());
}
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)
{
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
}
default:
return super.onOptionsItemSelected(item);
}
}
}
Now My problem. After i press back button onStop() code is executed and onDestroy. How i can don't kill app ? I wanna this app in background. Now when i press back button and open app, all data is again downloaded and loaded to webview. Soo how make this process work in background ?
Sorry for my haotic english :)
Sierran
Use Android service for doing something in Background rather then Activity.
And use Broadcast receiver to invoke your Activity from service. When something your background work finished.
Android - Service
And if you want to do some little then just override onKeyDown()
#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
return true;
}
return super.onKeyDown(keyCode, event);
}
I would recommend using a Service if you want to do something in the background and need it to be running more or less all the time. Check out the Service documentation here:
http://developer.android.com/reference/android/app/Service.html
An alternative in your case would be to create local caches of the websites.