Android enable back button in webview - java

I'm using the following code to display a webview in my Android app.
package com.company.myapp;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class ArticlesActivity extends Activity {
/** Initialize the Google Analytics Tracker */
GoogleAnalyticsTracker tracker;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
WebView webview = new WebView(this);
setContentView(webview);
setProgressBarVisibility(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
final Activity activity = this;
tracker = GoogleAnalyticsTracker.getInstance();
// Start the tracker, updating google every 20 seconds
tracker.start((String) getText(R.string.analyticsID), 20, this);
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 100 );
}
});
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl("http://www.google.com");
}
#Override
public void onResume() {
tracker.trackPageView("ArticlesActivity");
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Stop the tracker when it is no longer needed.
tracker.stop();
}
}
I would need to enable the back button to step back if history exists instead of just exiting the webview.
I've tried many different code examples such as this but can't get any to work. The app just shuts down when the back button is pressed.
Here's my code with the back button code but it just crashes the app when then back button is pressed:
package com.company.myapp;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class ArticlesActivity extends Activity {
WebView webview;
/** Initialize the Google Analytics Tracker */
GoogleAnalyticsTracker tracker;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
WebView webview = new WebView(this);
setContentView(webview);
setProgressBarVisibility(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
final Activity activity = this;
tracker = GoogleAnalyticsTracker.getInstance();
// Start the tracker, updating google every 20 seconds
tracker.start((String) getText(R.string.analyticsID), 20, this);
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 100 );
}
});
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl("http://www.google.com");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onResume() {
tracker.trackPageView("ArticlesActivity");
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Stop the tracker when it is no longer needed.
tracker.stop();
}
}
Could someone help me with a solution?

Got it! Your problem in this line
WebView webview = new WebView(this);
Instead of using your member variable you are creating a variable inside function, and hence your member variable is null inside onKeyDown function.
Just replace it with
webview = new WebView(this);

Related

How to hide Progress Bar in Android WebView

I am creating an Android project in which I have created a Webview. When the page loads, the progress bar runs. When the page is 100% loaded then the progress bar becomes hidden
But i don't know how to hide it
ProgressBar Code:
#Override
public void onProgressChanged(WebView view,int newProgress)
{
super.onProgressChanged(view, newProgress);
superProgressBar.setProgress(newProgress);
}
All Code:
package com.djaman.musicwala;
import android.app.*;
import android.os.*;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings;
import android.widget.ProgressBar;
import android.widget.ImageView;
import android.webkit.WebChromeClient;
import android.graphics.Bitmap;
import android.support.v7.app.ActionBar;
public class MainActivity extends Activity
{
ProgressBar superProgressBar;
ImageView superImageView;
WebView superWebView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
superWebView = (WebView) findViewById(R.id.webview);
superProgressBar = (ProgressBar) findViewById(R.id.myProcessBar);
superImageView = (ImageView) findViewById(R.id.myImageView);
superProgressBar.setMax(100);
superWebView.loadUrl("http://musicwala.cf");
superWebView.getSettings().setJavaScriptEnabled(true);
superWebView.setWebViewClient(new WebViewClient());
superWebView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view,int newProgress)
{
super.onProgressChanged(view, newProgress);
superProgressBar.setProgress(newProgress);
}
#Override
public void onReceivedTitle(WebView view,String title)
{
super.onReceivedTitle(view, title);
}
#Override
public void onReceivedIcon(WebView view,Bitmap icon)
{
super.onReceivedIcon(view, icon);
superImageView.setImageBitmap(icon);
}
});
}
private WebView findViewById()
{
// TODO: Implement this method
return null;
}
#Override
public void onBackPressed()
{
// TODO: Implement this method
if(superWebView.canGoBack())
{
superWebView.goBack();
}else{
super.onBackPressed();
}
}
}
you can try this in your "onProgressChanged()".
if (newProgress == 100) {
superProgressBar.setVisibility(View.GONE);
} else {
superProgressBar.setVisibility(View.VISIBLE);
superProgressBar.setProgress(newProgress);
}

Android webView doesn't come back after login on Facebook?

Im not and Android or Java Developer, I fullstack web developer..but I have a template for making webviews project that works in most of the cases...but with this login doesnt work..
I have a site tha use the facebook Js SDK Version 3.2
It works perfect on: Google Chrome in my Laptop.
It works perfect on: Google Chrome in my Phone
but in APP in the webView after i Insert user and password of Facebook and press login it freezes.
I think it cant return to the previous page..
I read a lot of post here but nothing works..
this is my MainActivity:
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String target_url = "https://myapp.com/gen_age/index.php";
private static final String target_url_prefix = "myapp.com/gen_age/index.php";
private WebView mWebview;
private WebView mWebviewPop;
private FrameLayout mContainer;
private SwipeRefreshLayout swipeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
mWebview = findViewById(R.id.webView);
mContainer = findViewById(R.id.webview_frame);
swipeLayout = findViewById(R.id.swipe_container);
final WebSettings webSettings = mWebview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
mWebview.setWebViewClient(new UriWebViewClient());
mWebview.setWebChromeClient(new UriChromeClient());
mWebview.loadUrl(target_url);
swipeLayout.setRefreshing(true);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
//Do your task
mWebview.reload();
}
});
}
private class UriWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
swipeLayout.setRefreshing(false);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
swipeLayout.setRefreshing(false);
}
#Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
swipeLayout.setRefreshing(false);
}
#Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
try {
String host = Uri.parse(url).getHost();
//Log.d("shouldOverrideUrlLoading", url);
if (host.equals(target_url_prefix)) {
// This is my web site, so do not override; let my WebView load
// the page
if (mWebviewPop != null) {
mWebviewPop.setVisibility(View.GONE);
mContainer.removeView(mWebviewPop);
mWebviewPop = null;
}
return false;
}
if (host.equals("m.facebook.com")) {
return false;
}
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
// swipeLayout.setRefreshing(false);
return true;
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
swipeLayout.setRefreshing(false);
Log.d("onReceivedSslError", "onReceivedSslError");
//super.onReceivedSslError(view, handler, error);
}
}
#Override
public void onBackPressed() {
if (mWebview.canGoBack()) {
mWebview.goBack();
} else {
finish();
}
}
class UriChromeClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
mWebviewPop = new WebView(getApplicationContext());
mWebviewPop.setVerticalScrollBarEnabled(false);
mWebviewPop.setHorizontalScrollBarEnabled(false);
mWebviewPop.setWebViewClient(new UriWebViewClient());
mWebviewPop.getSettings().setJavaScriptEnabled(true);
mWebviewPop.getSettings().setSavePassword(false);
mWebviewPop.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
mContainer.addView(mWebviewPop);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(mWebviewPop);
resultMsg.sendToTarget();
return true;
}
#Override
public void onCloseWindow(WebView window) {
Log.d("onCloseWindow", "called");
}
}
}
I'm gonna go out on a limb here and say you are doing IO operations (like trying to login by sending credentials over the internet) on the main UI thread. If this is the case, this is what is causing your app to freeze.
I couldn't find the actual code that is responsible for the login, but, if you are sending an HTTP request or something similar to it, you need to do it in a background thread, so that UI doesn't freeze.
The main thread in Android is responsible for updating the UI, and if you block it with a blocking IO operation, it will freeze.

How to open URL in an Activity (instead of a new browser)?

Can anyone please help me check my code to see why it cannot be
launched in the app itself but directs me to a browser? ): Thanks!!
MAIN ACTIVITY.JAVA
package com.intelligami.androidwebviewapp;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://intelligami.com/submitqn");
mWebView.setWebViewClient(new com.intelligami.androidwebviewapp.MyAppWebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
}});
}
private class MyWebViewClient extends MyAppWebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/** Inflating the current activity's menu with res/menu/items.xml */
getMenuInflater().inflate(R.menu.menu_main, menu);
/** Getting the actionprovider associated with the menu item whose id is share */
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
/** Setting a share intent */
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return super.onCreateOptionsMenu(menu);
}
/** Returns a share intent */
private Intent getDefaultShareIntent(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Convert Website to Android Application");
intent.putExtra(Intent.EXTRA_TEXT," Vist www.AndroidWebViewApp.com if you Want to Convert your Website or Blog to Android Application");
return intent;
}
}
MY APP VIEW CLIENT. JAVA
package com.intelligami.androidwebviewapp;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyAppWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("intelligami.com/submitqn")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
Where is the error? :D
It keeps opening up in the browser.
In the following line:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
you're asking Android to open a URL using the intent constant ACTION_VIEW - so it defaults to the external browser.
Here a full example (taken from here) that shows how to open the url using a WebViewClient:
package com.paresh.webviewclientdemo;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/*
* Demo of creating an application to open any URL inside the application and clicking on any link from that URl
should not open Native browser but that URL should open in the same screen.
*/
public class WebViewClientDemoActivity extends Activity {
/** Called when the activity is first created. */
WebView web;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
web = (WebView) findViewById(R.id.webview01);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("http://www.google.com");
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
web.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}

Non static method error on back button

I am trying to add a back button to app but when i add the code i get the "Non static method 'canGoBack() cannot be referenced from a static context" error. I have read several stack articles about this error but have not been able to solve it. Any ideas please?
package com.test;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import com.parse.ParseInstallation;
import com.parse.ParsePush;
import com.parse.ParseQuery;
import com.parse.PushService;
public class MainActivity extends Activity implements OnClickListener {
private Button push;
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "onReceive invoked!", Toast.LENGTH_LONG).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PushService.setDefaultPushCallback(this, MainActivity.class);
Button back = (Button) findViewById(R.id.back);
WebView webView = (WebView) findViewById(R.id.webView1);;
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.xxxxx.xxxxxx.xxxxx.xxxx// ");
webView.setWebViewClient(new WebViewClient());
push = (Button)findViewById(R.id.senPushB);
push.setOnClickListener(this);
}
private class Callback extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return (true);
}
}
#Override
public void onBackPressed()
{
if(WebView.canGoBack()){
WebView.goBack();
}else{
super.onBackPressed();
}
}
#Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
}
#Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, new IntentFilter(MyCustomReceiver.intentAction));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onClick(View v) {
JSONObject obj;
try {
obj = new JSONObject();
obj.put("alert", "hello!");
obj.put("action", MyCustomReceiver.intentAction);
obj.put("customdata","My message");
ParsePush push = new ParsePush();
ParseQuery query = ParseInstallation.getQuery();
// Push the notification to Android users
query.whereEqualTo("deviceType", "android");
push.setQuery(query);
push.setData(obj);
push.sendInBackground();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Try changing:
#Override
public void onBackPressed()
{
if(WebView.canGoBack()){
WebView.goBack();
}else{
super.onBackPressed();
}
}
to:
#Override
public void onBackPressed()
{
WebView webView = (WebView) findViewById(R.id.webView1);
if(webView.canGoBack()){
webView.goBack();
}else{
super.onBackPressed();
}
}
Explanation:
You should call canGoBack() and goBack() for the webview instance that you're using (move to the previous view). This is also why the method is declared at the instance level and not at the class level (static)
canGoBack is an instance (non-static) method. It can only be called on an instance of the WebView class. WebView is the class. Calling WebView.function() only works if function is a static function. You need to get the instance of the WebView and call it on that.
For the record, the difference between a static and instance method- a static method may not use any non-static data. An instance method can. Static data only has 1 copy per class. Non-static data has 1 copy per instance of the class.

Progress Status in Android App with Iframe a Site

I am building one app for my online radio station with iframe the site. But how I will add a progress status or animation image so that it's start on loading & end after load the site ? Here is the code I am using now:
package com.jibon.tarabradio;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends Activity {
#SuppressLint({ "SetJavaScriptEnabled", "NewApi" }) #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webview;
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
webview.loadUrl("http://hoicoimasti.com/radio/");
}
}
I also have another problem. When I select one country from drop down menu showing inside the app it's open different browser. How do I stop that & open inside the app ? Thanks in advance.
Just did it :) & solved other problem also :)
package com.jibon.tarabradio;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
WebView webview;
ProgressBar progressBar;
#SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webview);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
webview.setWebViewClient(new myWebClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
webview.loadUrl("http://hoicoimasti.com/radio/");
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
}

Categories

Resources