App stops when calling Webview back to Activity Intent - android

I developed a simple app that has two activities. When I call Menu activity to Webview using intent, it opens very well in web view, but when I click the button to return back to Activity, it crashes and asks to "close the app." Below is my java and it looks fine without errors. The log cat as well doesn't display any errors.
Who has the solution to these?
public class WebView extends AppCompatActivity {
WebView webView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
String url = getIntent().getStringExtra("site_url");
android.webkit.WebView webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setSupportZoom(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("" + url);
}
private class MywebClient extends WebViewClient {
#Override
public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
}
#Override
public void onBackPressed() {
android.webkit.WebView webView = null;
if(webView.isFocused() && webView.canGoBack())
{
webView.goBack();
}else{
super.onBackPressed();
}
}
}

Your problem is right here, in onBackPressed():
android.webkit.WebView webView = null;
if(webView.isFocused() && webView.canGoBack())
You set the variable webView to null and then you call a method isFocused() on it. That will cause a NullPointerException.
Change this to:
android.webkit.WebView webView = findViewById(R.id.webView);
if(webView.isFocused() && webView.canGoBack())

Related

Open new tabs on default browser when using webview

I want to tell you I never try android development before, and this is the first time I'm doing an android app I build a website using ASP.NET and I want to run that site within the android app web view.
So followed a few tutorials and I did so far.
Here when I redirect to some external sites In my site, I open them on another new tab on the browser, here I want to open it on the mobile phone's default browser instead of the opening inside the web view.
need a help to doing that.
This is my app MainActivity code.
public class MainActivity extends AppCompatActivity {
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView=findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.mycustom:5500/test/");
WebSettings websettings = webView.getSettings();
websettings.setJavaScriptEnabled(true);
}
private class MyWebView extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
}
#Override
public void onBackPressed() {
if (webView.isFocused() && webView.canGoBack()){
webView.goBack();
}else{
super.onBackPressed();
}
}
}

How to get Webview hyperlink to open in webview app instead of browser

I am trying to build a Webview app using android studio and I am currently having a problem. The index page shows perfectly on the app but whenever i click a hyperlink it redirects me to the browser and then to the website how can I get it to redirect me to another page whilst in the app built from webview. Here is a snippet of the main activity java
public class MainActivity extends AppCompatActivity {
private WebView mywebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mywebView = (WebView) findViewById(R.id.webview);
WebSettings websettings=mywebView.getSettings();
mywebView.loadUrl("https://www.cavaapperal.co.za/");
websettings.setJavaScriptEnabled(true);
}
public 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
public void onBackPressed (){
if (mywebView.canGoBack()) {
mywebView.goBack();
} else{
super.onBackPressed();
}
}
}
webView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {
return false;
}
}
});
WebView link click open default browser
Kindly see the following link

Don't navigate to other pages in WebView,disable links and references and go back to first page

I have a webView in Android and I open a html webpage in it. But it's full of links and images: when I click one of them it loads in my webview.I want to disable this behaviour, so if I click on a link, don't load it and go back to the first page.
I've tried this solution and edited a bit for myself, but it does not work:
webSettings.setJavaScriptEnabled(myWebViewClient.equals(true));
This opens a white page but I want to open the main URL. My webviewclient code:
public class MainActivity extends Activity {
public static String URL = "http://www.example.com/";
private WebView webView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.webView = (WebView) findViewById(R.id.webview);
MyWebViewClient myWebViewClient = new MyWebViewClient();
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(myWebViewClient.equals(true));
webView.reload();
webView.loadUrl(URL);
webSettings.setDisplayZoomControls(true);
webView.setWebViewClient(new WebViewClient());
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN) {
switch(keyCode) {
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack()){
webView.goBack();
return true;
}
break;
}
}
return super.onKeyDown(keyCode, event);
}
public void onBackPressed(){
if (webView.canGoBack()){
webView.goBack();
}
else{
super.onBackPressed();
}
}
}
you need to overwrite onPageStarted in WebViewClient:
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
//here check url i.e equals to your that html page
// if url equals not load url
and for go to back page check:
if(view.canGoBack())
// load first page url
}
You need a WebViewClient that overrides loading url:
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// url is the url to be loaded
return true; // override url (don't load it)
return false; // let url load
}
});
You can always return true to stay on the same page.
To open Main Url and stay on it, use this:
webview.loadUrl(MainUrl);
and then override loading url and always return true:
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return true;
}
});

Android WebView setting download folder location

I've added a webview activity and would like to control which folder any downloaded that my end users will download via my app. The files will be pdf files and I would like them to go into a specific folder that my app uses rather than the default download folder.
public class myweb extends Activity {
private WebView myWebView;
private String LOG_TAG = "AndroidWebViewActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.knitweb);
myWebView = (WebView) findViewById(R.id.webView1);
//enable Javascript
myWebView.getSettings().setJavaScriptEnabled(true);
//loads the WebView completely zoomed out
myWebView.getSettings().setLoadWithOverviewMode(true);
//true makes the Webview have a normal viewport such as a normal desktop browser
//when false the webview will have a viewport constrained to it's own dimensions
myWebView.getSettings().setUseWideViewPort(true);
//override the web client to open all links in the same webview
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.setWebChromeClient(new MyWebChromeClient());
//Injects the supplied Java object into this WebView. The object is injected into the
//JavaScript context of the main frame, using the supplied name. This allows the
//Java object's public methods to be accessed from JavaScript.
myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
//load the home page URL
//myWebView.loadUrl("http://demo.mysamplecode.com/Servlets_JSP/pages/androidWebView.jsp");
myWebView.loadUrl("http://www.patonsyarns.com/pattern.php?PID=4521&cps=21191");
myWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("demo.mysamplecode.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
private class MyWebChromeClient extends WebChromeClient {
//display alert message in Web View
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d(LOG_TAG, message);
new AlertDialog.Builder(view.getContext())
.setMessage(message).setCancelable(true).show();
result.confirm();
return true;
}
}
public class JavaScriptInterface {
Context mContext;
// Instantiate the interface and set the context
JavaScriptInterface(Context c) {
mContext = c;
}
//using Javascript to call the finish activity
public void closeMyActivity() {
finish();
}
}
//Web view has record of all pages visited so you can go back and forth
//just override the back button to go back in history if there is page
//available for display
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
I do not know in advance which files the users will be downloading other than that they will be pdf files.
Any help would be great
Thanks
I’m affraid the only solution is to use DownloadListener to catch the event and download the file manually.
Download a file example: http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/
DownloadListener example: How do I use DownloadListener?

Webview shouldoverrideurlloading doesn't work

I have this code in my app:
public class Home extends Activity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
final ProgressDialog progressBar;
if(isOnline()){
WebView webView = (WebView) findViewById(R.id.home_web);
webView.setBackgroundColor(Color.parseColor(getString(R.color.colore_bg)));
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setPluginsEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
progressBar = ProgressDialog.show(this,getString(R.string.caricamento),getString(R.string.attendere));
webView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
webView.loadUrl("http://www.mysite.com/android.php");
}else{
Toast.makeText(this,getString(R.string.no_connessione),Toast.LENGTH_LONG).show();
}
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("here");
if (Uri.parse(url).getHost().equals("mysite.com")) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
public boolean isOnline(){
ConnectivityManager cm=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if(ni==null){
return false;
}
return ni.isConnected();
}
}
The shouldOverrideUrlLoading doesn't work, neither print the system.out, it seems to be never called. How can I repair this? I need to open all the link (except the main page www.mysite.com/iphone.php) in the default browser
You've set the WebViewClient twice, thus replacing the first one (shouldOverrideUrlLoading) with the second one (onPageFinished). Combine the two for it to work:
public class Home extends Activity{
private ProgressDialog progressBar;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
if(isOnline()){
progressBar = ProgressDialog.show(this,getString(R.string.caricamento),getString(R.string.attendere));
WebView webView = (WebView) findViewById(R.id.home_web);
webView.setBackgroundColor(Color.parseColor(getString(R.color.colore_bg)));
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setPluginsEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl("http://www.mysite.com/android.php");
}else{
Toast.makeText(this,getString(R.string.no_connessione),Toast.LENGTH_LONG).show();
}
}
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
if (progressBar != null && progressBar.isShowing()) {
progressBar.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("here");
if (Uri.parse(url).getHost().equals("mysite.com")) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
}
(Please ignore the bad formatting :p)

Categories

Resources