i have a webview in which i want to add the functionality of changing the homepage through edit text field. like all the browsers do, but from other activity (i want to have this and all the other settings in another activity). is it possible to do so? Thanks
package com.example.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
private WebView webView;
private EditText urlEditText;
private ProgressBar progress;
private ToggleButton getToggleButton(int id) {
return (ToggleButton) findViewById(id);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getToggleButton(R.id.leave_toggle).setOnCheckedChangeListener(
new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton toggleButton,
boolean isChecked) {
if (isChecked) {
webView.getSettings().setLoadsImagesAutomatically(
false);// Enable Image
// Loading
} else {
webView.getSettings().setLoadsImagesAutomatically(
true);// Enable Image
// Loading
}
}
});
urlEditText = (EditText) findViewById(R.id.urlField);
webView = (WebView) findViewById(R.id.webView);
webView.setWebChromeClient(new MyWebViewClient());
webView.setDownloadListener(new DownloadListener() {// Download Manager
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
CookieManager.getInstance().setAcceptCookie(true);// Enable Cookies
webView.getSettings().setJavaScriptEnabled(true);// Enable Java Script
webView.setWebViewClient(new HelloWebViewClient());
webView.loadUrl("http://www.google.com/"); // Set
// Home
// page
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);// Remove
// ScrollBars
webView.getSettings().setDefaultFontSize(12);// Set Font Size
webView.getSettings().setPluginState(PluginState.ON);// Enable Flash
webView.setBackgroundColor(0x00000000);// Transparent Screen When
// Loading
webView.getSettings().setBuiltInZoomControls(true);// Set Zoom
// Controls
webView.requestFocus(View.FOCUS_DOWN);// Enable WebView Interaction
webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);// Set Cache
// (8mb)
String appCachePath = getApplicationContext().getCacheDir()
.getAbsolutePath();// Set Cache (8mb)
webView.getSettings().setAppCachePath(appCachePath);// Set Cache (8mb)
webView.getSettings().setAllowFileAccess(true);// Set Cache (8mb)
webView.getSettings().setAppCacheEnabled(true);// Set Cache (8mb)
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);// Set
// Cache
// (8mb)
webView.setWebViewClient(new WebViewClient() {// Open URL on Error
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {// Open URL on Error
Intent intent = new Intent(MainActivity.this, Error.class);
startActivity(intent);
}
});
// ////8888888888888888**URL BAR AND PROGRESS
// BAR**888888888888888888888888888888888
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
Button openUrl = (Button) findViewById(R.id.goButton);
openUrl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String url = urlEditText.getText().toString();
if (url.endsWith(".ac") || url.endsWith(".ac.uk")
if (!url.startsWith("http://")
&& !url.startsWith("https://")) {
url = "http://" + url;
}
}
if (validateUrl(url)) {
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
MainActivity.this.progress.setProgress(10);
}
}
private boolean validateUrl(String url) {
return true;
}
});
}
private class MyWebViewClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
MainActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
// ////8888888888888888**URL BAR AND PROGRESS
// BAR**888888888888888888888888888888888
class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url) {
webview.loadUrl(url);
return true;
}
}
public void forward(View view) { // Forward Button
Toast toast = Toast.makeText(this, "Forward", Toast.LENGTH_LONG);
toast.show();
webView.goForward();
}
public void back(View view) { // Back Button
Toast toast = Toast.makeText(this, "Back", Toast.LENGTH_LONG);
toast.show();
webView.goBack();
}
public void stop(View view) { // Stop Button
Toast toast = Toast.makeText(this, "Stop", Toast.LENGTH_LONG);
toast.show();
webView.stopLoading();
}
public void reload(View view) { // Reload Button
Toast toast = Toast.makeText(this, "Reloading..", Toast.LENGTH_LONG);
toast.show();
webView.reload();
}
// Tools navigation
public void database(View view) {
Intent intent = new Intent(this, Edt_Txt.class);
Toast toast = Toast.makeText(this, "Memory", Toast.LENGTH_LONG);
toast.show();
startActivity(intent);
}
public void mini(View view) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Toast toast = Toast.makeText(this, "Minimized", Toast.LENGTH_LONG);
toast.show();
startActivity(startMain);
}
public void json(View view) {
Intent intent = new Intent(this, JSON.class);
Toast toast = Toast.makeText(this, "Loading JSON (BETA)",
Toast.LENGTH_LONG);
toast.show();
startActivity(intent);
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
finish();
System.exit(0);
}
}).setNegativeButton("No", null).show();
}
}
This is code below when u click to set default url as home page :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("URL","http"//sample.com");
editor.apply();
When u set url to browser do this :
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String url= preferences.getString("URL","");
if(!name.equalsIgnoreCase(""))
{
//set url in broswer u will always get as last setted home page url
}
Related
I'm having a problem with my WebView-App.
I want to add a "Connection-check" on startup that's popping up an error when no Internet-connection is aviable or the WebView is timed out. I can't get it done by myself because I'm new in Android-programming.
I also want to add an options-menu where i can reload the actual page.
Hope someone can help me...
The actual code:
package com.sabithpkcmnr.webviewmaster;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ImageView superImageView;
ProgressBar superProgressBar;
WebView superWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayShowHomeEnabled(true);
superImageView = findViewById(R.id.myImageView);
superProgressBar = findViewById(R.id.myProgressBar);
superWebView = findViewById(R.id.myWebView);
superProgressBar.setMax(100);
superWebView.loadUrl("http://google.com");
superWebView.getSettings().setJavaScriptEnabled(true);
superWebView.setWebViewClient(new 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);
}
});
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);
getSupportActionBar().setTitle(title);
}
#Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
superImageView.setImageBitmap(icon);
}
});
superWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Uri myUri = Uri.parse(url);
Intent superIntent = new Intent(Intent.ACTION_VIEW);
superIntent.setData(myUri);
startActivity(superIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater myMenuInflater = getMenuInflater();
myMenuInflater.inflate(R.menu.super_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.myMenuOne:
onBackPressed();
break;
case R.id.myMenuTwo:
GoForward();
break;
case R.id.myMenuThree:
break;
}
return true;
}
private void GoForward() {
if (superWebView.canGoForward()) {
superWebView.goForward();
} else {
Toast.makeText(this, "Can't go further!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
if (superWebView.canGoBack()) {
superWebView.goBack();
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("(Exit?");
dialog.setMessage("Name has nothing to go back, so what next?");
dialog.setPositiveButton("EXIT ME", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.setCancelable(false);
dialog.setNegativeButton("STAY HERE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
}
Try below method by replacing your setWebViewClient,
superWebView= (WebView) findViewById(R.id.webView);
superWebView.setWebViewClient(new myWebClient());
superWebView.getSettings().setJavaScriptEnabled(true);
superWebView.loadUrl("LOAD_YOUR_URL");
superWebView.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("about:blank");
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);
}
});
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;
}
}
Below method can be used to check internet connection.
public static boolean checkInternetConnection(Context context) {
ConnectivityManager con_manager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
return (con_manager.getActiveNetworkInfo() != null
&& con_manager.getActiveNetworkInfo().isAvailable()
&& con_manager.getActiveNetworkInfo().isConnected());
}
you can check internet connection before loading url in webview.
Check below code snippet.
if (checkInternetConnection(this)) {
superWebView.loadUrl("http://google.com");
}else{
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
}
I have Cache Manifest applied on HTML Page.
On Chrome Browser when Internet connection goes off, it redirects to cache mode.
Well, this is not the case with Android-Webview. It gives following error:
Webpage could not be loaded
net:ERR_NAME_NOT_RESOLVED
Have gone through various resources but none seems to help.
Below is the code am using:
package com.example.page;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.google.firebase.iid.FirebaseInstanceId;
public class MainActivity extends Activity {
public static WebView mWebview;
private android.content.Context Context;
private static String getIntentValue = null;
public static SharedPreferences sharedPreferences;
private ProgressDialog mProgressDialog;
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
private final static int FCR=1;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
mWebview.setWebViewClient(new Callback());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context = this;
String regId = FirebaseInstanceId.getInstance().getToken();
getIntentValue = getIntent().getStringExtra("value");
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet Connection!", Toast.LENGTH_LONG).show();
finish(); //Calling this method to close this activity when internet is not available.
} else {
mWebview = (WebView) findViewById(R.id.webview1);
WebSettings webSettings = mWebview.getSettings();
mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.setWebChromeClient(new WebChromeClient());
mWebview.setWebViewClient(new CustomWebViewClient());
//improve WebView Performance
mWebview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mWebview.getSettings().setAppCacheEnabled(false);
mWebview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
if(Build.VERSION.SDK_INT >=23 && (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}, 1);
}
mWebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setAllowFileAccess(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
// progress dialog
mProgressDialog = new ProgressDialog(Context);
if (sharedPreferences.getBoolean("isKeyGenerated", true)) {
if (getIntentValue != null) {
mWebview.loadUrl("http://www.example.com/page");
getIntentValue = null;
} else {
mWebview.loadUrl("http://www.example.com/page2");
}
}
}
}
public class Callback extends WebViewClient{
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
}
}
// Function to load all URLs in same webview
private class CustomWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains(".pdf")) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
//on page started, show loading page
mProgressDialog.setCancelable(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.show();
}
#Override
public void onPageFinished(WebView view, String url)
{
String currentPage= mWebview.getUrl();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("currentpage",currentPage);
editor.commit();
//after loading page, remove loading page
// TODO Auto-generated method stub
super.onPageFinished(view, url);
mProgressDialog.dismiss();
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
view.loadUrl("http://example.com/page");
}
}
#Override
public void onBackPressed() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String currenturl = sharedPreferences.getString("currentpage", null);
mWebview.requestFocus();
if (currenturl.contains("http://example.com/page")){
moveTaskToBack(true);
}else{
mWebview.goBack();
}
if (mWebview.canGoBack()) {
if (!DetectConnection.checkInternetConnection(Context)) {
Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show();
}
}
}
public static void loadUrl(String key) {
if (getIntentValue != null) {
mWebview.loadUrl("http://example.com/page");
getIntentValue = null;
} else {
mWebview.loadUrl("http://example.com/page");
}
}
public static void reLoad() {
mWebview.reload();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
}
Just include enableHTML5AppCache()
private void enableHTML5AppCache() {
mWebview.getSettings().setDomStorageEnabled(true);
mWebview.getSettings().setAppCachePath("/data/data/" + getPackageName() + "/cache");
mWebview.getSettings().setAppCacheEnabled(true);
mWebview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
mWebview.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK)
This will tell the WebView to load the page from cache, but if it needs anything that isn't in the cache, it looks to the network, and when you have no connection, it will just give you the "page could not be loaded error." This is because sadly not everything is stored in the cache and even with this setting, you will notice the browser using the network.
Use WebSettings.LOAD_CACHE_ONLY
mWebview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY);
Change this line:
mWebview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
To:
mWebview.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK)
2021 update things have changed : Deprecated
The Application Cache API is deprecated and this method will become a no-op on all Android versions once support is removed in Chromium. Consider using Service Workers instead. See https://web.dev/appcache-removal/ for more information.
Read about service workers instead :) Happy Coding :P
I am trying to load the site in an android app web view.
The site loads without the images ,all the images from the site are not loaded and i can't add to the cart product or even open details of other product
The code for MainActivity.java is shown below.
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.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://shopliek.com");
mWebView.setWebViewClient(new 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);
}});
}
#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, "Make your Life Easier");
intent.putExtra(Intent.EXTRA_TEXT," Visit google");
return intent;
}
}
and also this MyAppWebViewClient:
public class MyAppWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("www.shopliek.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
I'm beginner so please explain kindly with simple instruction and thanks
Try this
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.google.com");
Hope this will work. Let me know if it works.
I've used the below code & everything worked correctly: show pictures, details page ... ...
public class WebviewActivity extends Activity {
#BindView(R.id.webview)
WebView web;
#BindView(R.id.progressBar)
ProgressBar progressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
ButterKnife.bind(this);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(WebserviceUrl.BASE_URL);
} catch (Exception e) {
e.printStackTrace();
}
}
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) {
progressBar.setVisibility(View.VISIBLE);
web.loadUrl(url);
return true;
}
public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
final AlertDialog.Builder builder = new AlertDialog.Builder(WebviewActivity.this);
builder.setMessage(R.string.notification_error_ssl_cert_invalid);
builder.setPositiveButton(R.string.continue_to_page, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.proceed();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.cancel();
}
});
final AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
}
try it & let me know the result
I have a webview, yes i do. :)
Anyway, I load my main URL fine, but i need to load another url programmatically at some point. The problem is that it somewhat opens another webview, and I know this because when I exit the app using finish() method, the webview with the latter url closes, but another webview stays open. What should I do? Should i call destroy webview or something else?
I just load them URLs using webview.loadUrl(url here) method.
Here's what's inside my main activity:
package com.sample;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity
{
private WebView wv;
private ProgressBar progress;
private static String mycaturl="*url 1*";
private static String helpurl="*url 2*";
private static String fbackurl="*url 3*";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
if (reachable(this))
{
Toast.makeText(this, "Reachable", Toast.LENGTH_SHORT).show();
buildwv( savedInstanceState, WebSettings.LOAD_DEFAULT, mycaturl );
}
else
{
Toast.makeText(this, "Unreachable", Toast.LENGTH_SHORT).show();
eolc( savedInstanceState );
}
}
#SuppressLint({ "SetJavaScriptEnabled" })
public void buildwv(Bundle sis, int load, String url)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
setContentView(R.layout.activity_main);
//assigning objects to variables
wv=(WebView) findViewById(R.id.wv);
wv.setWebViewClient( new wvc() );
progress=(ProgressBar) findViewById(R.id.progress);
//websettings
WebSettings ws = wv.getSettings();
ws.setAppCacheMaxSize( 100 * 1024 * 1024 ); // 100MB
ws.setAppCachePath( this.getCacheDir().getAbsolutePath() );
ws.setAllowFileAccess( true );
ws.setAppCacheEnabled( true );
ws.setJavaScriptEnabled( true );
ws.setCacheMode(load);
//if instance is saved, to catch orientation change
if(sis==null)
{ wv.loadUrl(url); }
}
public void eolc(final Bundle sis)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
AlertDialog.Builder alertDialog = new AlertDialog.Builder( MainActivity.this );
alertDialog.setTitle("Unreachable Host");
alertDialog.setMessage("Host is unreachable. Load from cache or exit.");
alertDialog.setIcon(R.drawable.tick);
//alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton( "Load from Cache", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to load cache.", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, mycaturl );
}
});
alertDialog.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help. EOLC", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, helpurl );
}
});
alertDialog.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.create();
alertDialog.show();
}
public void roe()
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
AlertDialog.Builder alertDialog = new AlertDialog.Builder( MainActivity.this );
alertDialog.setTitle("Connection Lost");
alertDialog.setMessage("Connection to host was lost. Restart and load cache or exit.");
alertDialog.setIcon(R.drawable.tick);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton( "Restart", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
Toast.makeText(getApplicationContext(), "You chose to restart and load cache.", Toast.LENGTH_SHORT).show();
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity(i);
}
});
alertDialog.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help. ROE", Toast.LENGTH_SHORT).show();
wv.stopLoading();
wv.loadUrl( helpurl );
}
});
alertDialog.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose to exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.create();
alertDialog.show();
}
private class wvc extends WebViewClient
{
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
progress.setVisibility(View.VISIBLE);
if (url.contains(mycaturl))
{
WebSettings ws = wv.getSettings();
if ( !reachable(getApplicationContext()) )
{
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
roe();
}
else if ( ws.getCacheMode() == WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(), "loading cache coz not reachable", Toast.LENGTH_SHORT).show();
}
}
else
{
if ( ws.getCacheMode() == WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(), "Connection to server established.", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
Toast.makeText(getApplicationContext(), "PAGE DONE LOADING!!", Toast.LENGTH_SHORT).show();
//circular progress bar close
progress.setVisibility(View.GONE);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
super.onReceivedError(view, errorCode, description, failingUrl);
wv.stopLoading();
WebSettings ws = wv.getSettings();
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
wv.loadUrl(helpurl);
Toast.makeText(getApplicationContext(), "Page unavailable", Toast.LENGTH_SHORT).show();
}
else
{
wv.loadUrl(helpurl);
Toast.makeText(getApplicationContext(), "Page not cached", Toast.LENGTH_SHORT).show();
}
roe();
}
}
//checking connectivity by checking if site is reachable
public static boolean reachable(Context context)
{
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
try
{
URL url = new URL(mycaturl);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(5000); // five seconds timeout in milliseconds
urlc.connect();
if (urlc.getResponseCode() == 200) // good response
{ return true; } else { return false; }
}
catch (IOException e)
{ return false; }
}
else
{ return false; }
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onBackPressed ()
{
if (wv.isFocused() && wv.canGoBack())
{ wv.goBack(); } else { finish(); }
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.item1:
wv.loadUrl( helpurl );
break;
case R.id.item2:
wv.loadUrl( fbackurl );
break;
case R.id.item3:
String currurl=wv.getUrl();
wv.loadUrl(currurl);
break;
case R.id.item4:
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
break;
case R.id.item5:
finish();
break;
default:
break;
}
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState )
{
super.onSaveInstanceState(outState);
wv.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
wv.restoreState(savedInstanceState);
}
}
Should I also include manifest? Thanks in advance.
Put this in your web Activity :
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Then set :
your_webview.setWebViewClient(new MyWebViewClient());
Hope this will help you
Without the necessary code I have to assume this is what you need to add to your implementation.
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
webview.loadUrl(url);
return true;
}
I am running into trouble in shouldoverrideurlloading method, wherein the URL being overridden is not being shown. Instead, a blank white screen is coming up, and Logcat shows no errors. I have provided code below . WHere am I making a mistake? Please advise
package com.example.webviewkm;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.View;
import android.webkit.HttpAuthHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.net.http.SslError;
import android.webkit.SslErrorHandler;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView) findViewById(R.id.MyWebView);
webView.setInitialScale(67);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setVerticalScrollBarEnabled(false);
webView.setHorizontalScrollBarEnabled(false);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedLoginRequest(WebView view, String realm,
String account, String args) {
System.err.println(realm);
System.err.println(account);
System.out.println(args); }
#Override
public void onReceivedError( WebView view, int errorCode, String description, String failingUrl ) {
Toast.makeText(view.getContext(), "Unknown Error", Toast.LENGTH_LONG).show();
System.err.println(errorCode + " - " + description + "-" + failingUrl);
}
#Override
public void onReceivedSslError( WebView view, SslErrorHandler handler, SslError error ) {
System.err.println("SSL ERROR");
handler.proceed();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
intent.putExtra("url", url);
startActivity(intent);
return true;
}
#Override
public void onReceivedHttpAuthRequest(WebView view, final HttpAuthHandler handler, final String host,
String realm) {
System.err.println("HTTP auth request");
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
if (handler.useHttpAuthUsernamePassword()) {
if (preferences.contains("username")) {
handler.proceed(preferences.getString("username", null), preferences.getString("password", null));
return;
}
}
new Dialog(MainActivity.this){
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(host);
setContentView(R.layout.credentials);
final EditText userName = (EditText) findViewById(R.id.UserName);
final EditText password = (EditText) findViewById(R.id.Password);
userName.setText(preferences.getString("username", ""));
password.setText(preferences.getString("password", ""));
Button button = (Button) findViewById(R.id.GoButton);
button.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
String userName2 = userName.getText().toString();
String password2 = password.getText().toString();
Editor edit = preferences.edit();
edit.putString("username", userName2);
edit.putString("password", password2);
edit.commit();
handler.proceed(userName2, password2);
dismiss();
}});
}
}.show();
}
});
String url;
if (getIntent().hasExtra("url")) {
url = getIntent().getStringExtra("url");
} else {
url = "https://kee.mahindrasatyam.com/_layouts/mobile/mobilesearch.aspx";
}
webView.loadUrl(url);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
return true;
}
}
In your Code pasted below in the method shouldOverrideUrlLoading,
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
intent.putExtra("url", url);
startActivity(intent);
return true;
}
You are just Starting the same Activity and you are passing the url as intent extra ,this will not load the url in webview neither it will give you an error , and if you are intending to load the url in the webview use
webView.loadUrl(url) in shouldOverrideUrlLoading method.