Shouldoverrideurlloading method in android - android

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.

Related

How to get information when some one change the value in edittext in android Studio

As I have the next button and webview which is attached with the webview. And My website refreshes with the value upgradation, But when someone types the value in the text field app web view doesn't reload. So please help me to reload my webview when the value is changed or typed new value thank you.
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class phy_btn extends AppCompatActivity {
TextView justme;
EditText data;
Button btn, next;
String half;
String i, nuller;
public static String Extra_name = "1";
WebView webView;
NetworkChangeListener networkChangeListener = new NetworkChangeListener();
#Override
protected void onStart() {
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkChangeListener, filter);
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_btn);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.toolbar_title);
// justme = findViewById(R.id.nit);
query quu = new query(this);
data = findViewById(R.id.enter);
btn=findViewById(R.id.previous);
next= findViewById(R.id.next);
i = "1";
webView =findViewById(R.id.web);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.setKeepScreenOn(true);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.getSettings().setAppCacheEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Practical");
getSupportActionBar().setSubtitle("Physical Botany");
enter code here
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
quu.linkker( new query.VolleyCallback(){
#Override
public void linkker(String date, String numer, String answer1, String imag1) {
i = data.getText().toString();
int value = Integer.parseInt(i);
value++;
String nepali = Integer.toString(value);
half = date.split(".app/")[0];
String killer = half+".app/btnphy/"+nepali+".html";
data.setText(nepali);
webView.loadUrl(killer);
}
});
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
quu.linkker( new query.VolleyCallback(){
#Override
public void linkker(String date, String numer, String answer1, String imag1) {
i = data.getText().toString();
int value = Integer.parseInt(i);
value--;
String nepali = Integer.toString(value);
half = date.split(".app/")[0];
String killer = half+".app/btnphy/"+nepali+".html";
data.setText(nepali);
webView.loadUrl(killer);
if (i != "1") {
webView.loadUrl(killer);
}
}
});
}
});
quu.linkker( new query.VolleyCallback(){
#Override
public void linkker(String date, String numer, String answer1, String imag1) {
half = date.split(".app/")[0];
String killer = half+".app/btnphy/"+i+".html";
// justme.setText(killer);
if (i != "1") {
webView.loadUrl(killer);
}
webView.loadUrl(killer);
}
});
}
}

How to Load Cache Page in Webview

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

WebView based app, YouTube videos does not have full screen button

I have a WebView based app that shows a WordPress website. I have in my website a few YouTube videos, and the problem is YouTube videos does not have full screen button. I looked for an answer to this and didn't find anything on the web. Can someone help me? how can I make the YouTube videos have the option to play in full screen from my WebView?
Here is my MainActivity code:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import com.delitestudio.pushnotifications.PushNotifications;
import com.loopj.android.http.*;
import cz.msebera.android.httpclient.*;
import cz.msebera.android.httpclient.impl.entity.StrictContentLengthStrategy;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final WebChromeClient webChromeClient = new WebChromeClient();
private static final WebViewClient webViewClient = new WebViewClient();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url;
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey("fromPush")) {
url = "http://www.paotiptipon.co.il/%d7%9b%d7%a0%d7%99%d7%a1%d7%aa-%d7%94%d7%95%d7%a8%d7%99%d7%9d-2/%d7%a4%d7%95%d7%a1%d7%98%d7%99%d7%9d/";
WebView myWebView = (WebView) findViewById(R.id.webView);
myWebView.loadUrl(url);
} else {
url = "http://paotiptipon.co.il/";
}
WebView myWebView = (WebView) this.findViewById(R.id.webView);
myWebView.setWebViewClient(new WebViewClient());
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebChromeClient(webChromeClient);
myWebView.setWebViewClient(webViewClient);
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.getSettings().setAllowContentAccess(true);
myWebView.getSettings().setDatabaseEnabled(true);
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.loadUrl(url);
myWebView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack())
webView.goBack();
break;
}
}
return false;
}
});
notificationsButtonClicked();
newNotificationButtonClicked();
calendarButtonClicked();
final PushNotifications pn = new PushNotifications(this);
if (pn.getToken() == null || pn.isExpired()) {
pn.refreshToken("http://www.paotiptipon.co.il/pnfw/register/",
"35299935473");
}
// Bundle extras = getIntent().getExtras();
// if (extras != null) {
// int id = extras.getInt(PushNotifications.ID);
// String title = extras.getString(PushNotifications.TITLE);
// System.out.println(id + title);
// }
}
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mIntentReceiver.abortBroadcast();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("התראה חדשה!");
alertDialog.setMessage("יש התראה חדשה במרכז ההתראות! לחצו על אישור כדי לראות אותה!");
// Setting OK Button
alertDialog.setPositiveButton("אישור",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String url = "http://www.paotiptipon.co.il/%d7%9b%d7%a0%d7%99%d7%a1%d7%aa-%d7%94%d7%95%d7%a8%d7%99%d7%9d-2/%d7%a4%d7%95%d7%a1%d7%98%d7%99%d7%9d/";
WebView myWebView = (WebView) findViewById(R.id.webView);
myWebView.loadUrl(url);
}
});
// Setting CANCEL Button
alertDialog.setNegativeButton("ביטול",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
alertDialog.show();
}
};
private void notificationsButtonClicked() {
Button notifications = (Button) findViewById(R.id.notifications);
notifications.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://www.paotiptipon.co.il/%d7%9b%d7%a0%d7%99%d7%a1%d7%aa-%d7%94%d7%95%d7%a8%d7%99%d7%9d-2/%d7%a4%d7%95%d7%a1%d7%98%d7%99%d7%9d/";
WebView myWebView = (WebView) findViewById(R.id.webView);
myWebView.loadUrl(url);
}
});
}
private void newNotificationButtonClicked() {
Button newNotification = (Button) findViewById(R.id.newNotification);
newNotification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://www.paotiptipon.co.il/wp-admin/post-new.php";
WebView myWebView = (WebView) findViewById(R.id.webView);
myWebView.loadUrl(url);
}
});
}
private void calendarButtonClicked() {
Button calendar = (Button) findViewById(R.id.calendar);
calendar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://www.paotiptipon.co.il/events/";
WebView myWebView = (WebView) findViewById(R.id.webView);
myWebView.loadUrl(url);
}
});
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mIntentReceiver, PushNotifications.getIntentFilter(this));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mIntentReceiver);
}
}
first of all thanks for those of you who tried to help.
I found an answer to my question, and I would like to share it here so if anyone needs this it will be here.
I used this link:
Playing HTML5 video on fullscreen in android webview
I just downloaded the example project from there and implemented the code there in my project. The man who wrote those classes is awesome and wrote a really good tutorial on this and it fixed my problem. :)

On Button Click Get contents from a WebView textarea Android

I've searched on google and stackoverflow but cannot find any solutions relevant to Android API 17 and above.
I like to retrieve data from a webview on Button Click.
I like to achieve something similar to what ios has:
myText.stringByEvaluatingJavaScriptFromString
("document.getElementById('chapter-description').value")
my source code is:
package com.xyz.webviewtest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
public class MainActivity4 extends AppCompatActivity {
TextView textView;
#SuppressLint("JavascriptInterface")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WebView webview = (WebView) findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:window.HtmlViewer.showHTML" +
"('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
}
});
// new MyJavaScriptInterface(this).showHTML("HtmlViewer");
webview.loadUrl("http://www.xsoftech.com");
}
class MyJavaScriptInterface {
private Context ctx;
MyJavaScriptInterface(Context ctx) {
this.ctx = ctx;
}
public void showHTML(String html) {
new AlertDialog.Builder(ctx).setTitle("HTML").setMessage(html)
.setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show();
}
}
}
http://developer.android.com/ states that the constructor is deprecated
This constructor was deprecated in API level 17. Private browsing is
no longer supported directly via WebView and will be removed in a
future release. Prefer using WebSettings, WebViewDatabase,
CookieManager and WebStorage for fine-grained control of privacy data.
Webview have textarea so i can write something after writing i want able to get data on button click. Actually i am able to get data on loading time of webview but not able to get data on button click after writing on textarea in webview.
I found a possible solution, but I am not able to get any data on button click.
The solution is:
package example.xsoftech.sample;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
public class Main2 extends Activity {
WebView webview1;
public static String data;
Button button;
String sUrl = "http://www.facebook.com/";
// String sUrl = "http://www.xsoftech.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)findViewById(R.id.button);
webview1 = (WebView)findViewById(R.id.myWebview);
webview1.getSettings().setJavaScriptEnabled(true);
webview1.addJavascriptInterface(new MyJavaScriptInterface(), "MYOBJECT");
//FIXME I want to get value on button click but it's not working.So plz give me solution for work it?
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Main2.this, "click is done: "+data, Toast.LENGTH_SHORT).show();
data= "";
webview1.loadUrl(sUrl);
}
});
webview1.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("lifecyle", "shouldOverrideUrlLoading");
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d("lifecyle", "onpagefinished");
StringBuilder sb = new StringBuilder();
sb.append("document.getElementsByTagName('form')[0].onsubmit = function () {");
sb.append("var objPWD, objAccount;var str = '';");
sb.append("var inputs = document.getElementsByTagName('input');");
sb.append("for (var i = 0; i < inputs.length; i++) {");
sb.append("if (inputs[i].type.toLowerCase() === 'password') {objPWD = inputs[i];}");
sb.append("else if (inputs[i].name.toLowerCase() === 'email') {objAccount = inputs[i];}");
sb.append("}");
sb.append("if (objAccount != null) {str += objAccount.value;}");
sb.append("if (objPWD != null) { str += ' , ' + objPWD.value;}");
sb.append("window.MYOBJECT.processHTML(str);");
sb.append("return true;");
sb.append("};");
view.loadUrl("javascript:" + sb.toString());
}
});
webview1.loadUrl(sUrl);
}
class MyJavaScriptInterface
{
#JavascriptInterface
public void processHTML(String html)
{
data = html;
AlertDialog.Builder builder = new AlertDialog.Builder(Main2.this);
builder.setTitle("AlertDialog from app")
.setMessage(html)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
})
.setCancelable(false).show();
}
}
}
any help is appreciated.
I am really happy to giving answer
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)findViewById(R.id.button);
final WebView browser = (WebView)findViewById(R.id.myWebview);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);
/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
// This call inject JavaScript into the page which just finished loading.
browser.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementsByTagName('textarea')[0].innerHTML);");
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
browser.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementById('chapter-description').value);");
}
});
/* load a web page */
browser.loadUrl(sUrl);
}
Enable javascript
Add your own javascript
Register your own webviewClient, overriding the onPageFinished to insert a bit of javascript
In the javascript, acquire the element.innerText of the tag, and pass it to your javascript interface.

How to set Homepage in WebView from edit text?

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
}

Categories

Resources