Android App Linking not working inside the WebView - android

When I try with the phone browser it opens the app. but not inside of the app webview.
public class WebViewPayNowFragment extends Fragment implements AdvancedWebView.Listener {
private View rootView;
private AdvancedWebView mWebView;
private String link, tid;
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("asdajsda : "+url);
if (url != null && url.startsWith("ptcl://")) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {
return false;
}
}
}
public WebViewPayNowFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
if (bundle != null) {
link = bundle.getString(Constants.LINK, null);
tid = bundle.getString(Constants.TRANSACTION_ID, null);
System.out.println("asdiahsdhakjshdkah : " + link);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_web_view, container, false);
mWebView = rootView.findViewById(R.id.webview);
mWebView.setListener(getActivity(), this);
mWebView.setWebViewClient(new MyBrowser());
if (link != null) {
String postData = null;
try {
postData = "TransactionID=" + URLEncoder.encode(tid, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
mWebView.postUrl(link, postData.getBytes());
} else {
}
return rootView;
}
Here is my code inside the fragment.
I created a inner class extending WebViewClient. and set the setWebViewClient but im still having the problem.

Solution:
I encountered this situation myself. This is what I did:
First create a inner class and extend it with WebViewClient:
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
....
}
}
then:
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && url.startsWith("ptcl://")) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {
return false;
}
}
Lastly,
webView.setWebViewClient(new MyBrowser());
Try it, Hope it helps.

Related

Remove Header and Footer in WebView Amdroid

I want to remove the header and footer before loading the content to the web view. This code isn't working. I have boutique website. My code remove header and footer when load url in webview. When i click any boutique,it load details page with header and footer, it does not remove from inner pages
public class WebviewFragment extends Fragment implements IOnBackPressed {
WebSettings ws;
WebView webView;
Document document;
// TODO: Rename and change types of parameters
private String url;
public WebviewFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_webview, container, false);
webView = (WebView) v.findViewById(R.id.webView);
url = getArguments().getString("url");
new MyAsynTask().execute();
return v;
}
#Override
public boolean onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
return true;
} else {
// activity will act normal
return false;
}
}
private class MyAsynTask extends AsyncTask<Void, Void, Document> {
#Override
protected Document doInBackground(Void... voids) {
Document document = null;
try {
document = Jsoup.connect(url).get();
document.getElementById("header").remove();
document.getElementById("footer").remove();
} catch (IOException e) {
e.printStackTrace();
}
return document;
}
#Override
protected void onPostExecute(Document document) {
super.onPostExecute(document);
webView.loadDataWithBaseURL(url, document.toString(), "text/html", "utf-8", "");
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
// webView.loadUrl(url);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String request) {
view.loadUrl(request);
return super.shouldOverrideUrlLoading(view, request);
}
#Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:var footer = document.getElementById(\"footer\"); footer.parentNode.removeChild(footer); var header = document.getElementById(\"header-full\"); header.parentNode.removeChild(header);");
}
});
}
}
}
Please help me out, I shall be very thankful to you.

How to clear Http Basic Auth username and password from cache - android webview

I am using android webview to display a web page that requires basic authentication. I have the code that takes in username and password and allows successful login to the web page. But I want to clear the username and password from cache when the user visits the webview again. Looks like once you enter username and password for basic auth, it keeps that in cache and logs you in automatically.
I have tried
WebViewDatabase webViewDB = WebViewDatabase.getInstance(getActivity());
webViewDB.clearHttpAuthUsernamePassword();
I have also tried webview.clearFormData, webview.clearCache
But it doesn't seem to work. It logged me in automatically without the prompt to enter username and password.
Here is my full code for webview fragment.
public class WebViewFragment extends Fragment {
private static final String LOG_TAG = WebViewFragment.class.getName();
private ProgressBar progressBar;
private View footerV;
private String urlToLoad;
private int footerVisibility;
private int failureCount = 0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.web_fragment, container, false);
try {
init(rootView);
} catch (Exception e) {
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getActivity()));
}
return rootView;
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (footerV != null) footerV.setVisibility(footerVisibility);
}
private void init(View rootView) {
Bundle bundle = getArguments();
ConstraintLayout navBarCL = (ConstraintLayout) rootView.findViewById(R.id.navBar);
progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
if (bundle.getBoolean(BundleConstants.WEB_HIDE_HEADER)) {
navBarCL.setVisibility(View.GONE);
} else {
navBarCL.setVisibility(View.VISIBLE);
ImageView backButtonIV = (ImageView) rootView.findViewById(R.id.backButtonImage);
backButtonIV.setOnClickListener(view -> navigateBack());
String title = bundle.getString(BundleConstants.WEB_HEADER_TEXT);
TextView headerTextTV = (TextView) rootView.findViewById(R.id.headerText);
headerTextTV.setText(title);
}
WebView webView = (WebView) rootView.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setWebViewClient(getClient());
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onCloseWindow(WebView window) {
super.onCloseWindow(window);
navigateBack();
}
});
footerV = getActivity().findViewById(R.id.footer);
footerVisibility = footerV.getVisibility();
if (bundle.getBoolean(BundleConstants.WEB_SHOW_FOOTER)) {
footerV.setVisibility(View.VISIBLE);
} else {
footerV.setVisibility(View.GONE);
}
urlToLoad = bundle.getString(BundleConstants.WEB_URL);
Log.d(LOG_TAG, "Opening url :" + urlToLoad);
webView.loadUrl(urlToLoad);
}
#NonNull
private WebViewClient getClient() {
WebViewDatabase webViewDB = WebViewDatabase.getInstance(getActivity());
webViewDB.clearHttpAuthUsernamePassword();
return new WebViewClient() {
#Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
++failureCount;
showProgressBar();
LoginDialog loginDialog = new LoginDialog(getContext(), getFragment(), handler, failureCount);
loginDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
hideProgressBar();
}
};
}
public void hideProgressBar() {
if (progressBar != null) progressBar.setVisibility(View.GONE);
}
public void showProgressBar() {
if (progressBar != null) progressBar.setVisibility(View.VISIBLE);
}
private WebViewFragment getFragment() {
return this;
}
public String getUrlToLoad() {
return urlToLoad;
}
protected void navigateBack() {
footerV.setVisibility(footerVisibility);
getFragmentManager().popBackStack();
}
}
Please provide some suggestions.
Try this
WebView webView = (WebView) rootView.findViewById(R.id.webView);
webView.clearCache(true);

Android download file with webview

I have app's MainActivity like this, and this app can't download file with webview
Anybody knows how to fix the download problem?
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Webkit;
namespace REC
{
[Activity(Label = "APPNAME", MainLauncher = true, Icon = "#drawable/rec512", ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
public class MainActivity : Activity
{
private WebView mWebView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
RequestWindowFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.Main);
mWebView = FindViewById<WebView>(Resource.Id.webview);
mWebView.Settings.SetRenderPriority(WebSettings.RenderPriority.High);
mWebView.Settings.JavaScriptEnabled = true;
mWebView.LoadUrl("http://www.APPname.com");
mWebView.SetWebViewClient(new WebViewClient());
// mWebView.SetDownloadListener(new MyDownloadListener()
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = (WebRequest)base.GetWebRequest(address);
// Perform any customizations on the request.
// This version of WebClient always preauthenticates.
request.PreAuthenticate = true;
return request;
}
class MonkeyWebChromeClient : WebChromeClient
{
public override bool OnJsAlert(WebView view, string url, string message, JsResult result)
{
return base.OnJsAlert(view, url, message, result);
}
public override Boolean OnJsConfirm(WebView view, String url, String message, JsResult result)
{
return base.OnJsConfirm(view, url, message, result);
}
public override Boolean OnJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result)
{
return base.OnJsPrompt(view, url, message, defaultValue, result);
}
}
public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
{
if (keyCode == Keycode.Back && mWebView.CanGoBack())
{
mWebView.GoBack();
return true;
}
return base.OnKeyDown(keyCode, e);
}
}
public class WebClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
//return base.ShouldOverrideUrlLoading(view, url);
view.LoadUrl(url);
return true;
}
internal object GetWebRequest(Uri address)
{
throw new NotImplementedException();
}
}
}
You did not implement webview download listener,please refer to the following code :
public class MainActivity : Activity
{
WebView wv1;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
wv1 = FindViewById<WebView>(Resource.Id.webView1);
wv1.SetDownloadListener(new MyDownloadListerner(this));
wv1.LoadUrl("https://notepad-plus-plus.org/download/v7.3.2.html");
}
class MyDownloadListerner : Java.Lang.Object, IDownloadListener
{
Context cont;
public MyDownloadListerner(Context context)
{
cont = context;
}
public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
{
Android.Net.Uri uri = Android.Net.Uri.Parse(url);
Intent intent = new Intent(Intent.ActionView,uri);
cont.StartActivity(intent);
}
}
}
Note: This method is start another browser to download, you can also create a new thread to download file at the OnDownloadStart function.
screen shot:
Please follow the following code
public class WebViewFragment extends KaROFragment {
private WebView mWebView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_webview, container, false);
try {
mWebView = (WebView) view.findViewById(R.id.webView);
mWebView.setWebViewClient(new myWebClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.loadUrl("https://www.google.com/");
} catch (Exception e) {
e.getStackTrace();
}
return view;
}
public class myWebClient extends WebViewClient {
#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);
}
}
public void downloadAndPrintDocument(WebView webView, String title) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
PrintManager printManager = (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE);
//noinspection deprecation
PrintDocumentAdapter printDocumentAdapter = webView.createPrintDocumentAdapter();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
printDocumentAdapter = webView.createPrintDocumentAdapter(title);
String documentName = title;
PrintJob printJob = printManager.print(documentName, printDocumentAdapter, new PrintAttributes.Builder().build());
List<PrintJob> printJobs = printManager.getPrintJobs();
printJobs.add(printJob);
} else {
// mContext.showToast(mContext.getString(R.string.mytools_printing_not_supported), 1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Android-Webview loadurl in next activity

I am having a WebView and i am getting data in it from a WebService.
my problem is, there are so many url's in the data i am getting and when a user click on it, then it should load on a WebViewon next page not on a browser.
How can i achieve that.? I tried shouldOverrideUrlLoading but it's not working.
Try this.
public class WebViewActivity extends Activity {
private ProgressDialog progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressBar = ProgressDialog.show(this, "Hi", "me");
WebView webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl("http://www.mysite.com/android.php");
}
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");
//Upadated code..........
Bundle bundle = new Bundle();
//Add your data from getFactualResults method to bundle
bundle.putString("NextUrl", url);
Intent i = new Intent(WebViewActivity.this, NextActivity.class);
i.putExtras(bundle);
startActivity(i);
//-----------------------
Log.i("Hi", "WEb nextttt");
return true;
}
}
}
NextActivity
public class NextActivity extends Activity {
WebView wv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Bundle bundle = getIntent().getExtras();
//Extract the data…
String url = bundle.getString("NextUrl");
Log.i("Hi", "Get next");
wv1 = (WebView) findViewById(R.id.webView1);
wv1.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
wv1.getSettings().setSupportZoom(false);
wv1.getSettings().setSupportMultipleWindows(false);
wv1.setHorizontalScrollBarEnabled(false);
wv1.setVerticalScrollBarEnabled(false);
wv1.getSettings().setUseWideViewPort(true);
wv1.getSettings().setLoadWithOverviewMode(true);
wv1.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView viewx, String urlx) {
viewx.loadUrl(urlx);
return false;
}
});
try {
wv1.loadUrl(url);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Android WebView shows plain text

I have a WebView and I load the page using webView.loadUrl("http://myurl.com") and the page gets shown correct on android 4.X but while trying on 2.X, more specifically 2.3.5 a plain text gets displayed similar to this
What might be the problem and how do I fix it? Thanks!
My full code:
public class FragmentPolicy extends SherlockFragment implements Refreshable {
private WebView webView;
private Bundle webViewBundle;
private UpdateReceiver updateReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateReceiver = new UpdateReceiver();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.fragment_policy, container, false);
webView = (WebView) ll.findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.startsWith("mailto:")){
MailTo mt = MailTo.parse(url);
Intent i = newEmailIntent(getSherlockActivity(), mt.getTo(), mt.getSubject(), mt.getBody(), mt.getCc());
startActivity(i);
view.reload();
return true;
} else {
view.loadUrl(url);
}
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.stopLoading();
webView.clearView();
Log.w("test", "Could not get policy: " + description + " Errror code: " + errorCode + ". Url: " + failingUrl);
}
});
loadPolicy();
return ll;
}
private void loadPolicy(){
if (webViewBundle == null) {
Map<String, String> headers = new HashMap<String, String>();
//does not work with webview
headers.put("Content-Type", "text/html; charset=utf-8");
headers.put("Accept", "text/html");
webView.loadUrl(Utils.getBaseAPIAddr()+"getpolicyhtml", headers);
//webView.loadData(URLEncoder.encode(result).replaceAll("\\+", " "), "text/html", Encoding.UTF_8.toString());
} else {
webView.restoreState(webViewBundle);
}
}
private Intent newEmailIntent(Context context, String address, String subject, String body, String cc) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, new String[] {address});
intent.putExtra(Intent.EXTRA_TEXT, body);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_CC, cc);
intent.setType("message/rfc822");
return intent;
}
#Override
public void onPause() {
super.onPause();
webViewBundle = new Bundle();
webView.saveState(webViewBundle);
}
#Override
public void onResume(){
super.onResume();
LocalBroadcastManager.getInstance(getSherlockActivity()).registerReceiver(updateReceiver, new IntentFilter("update"));
}
#Override
public void onStop(){
super.onStop();
if(updateReceiver != null){
LocalBroadcastManager.getInstance(getSherlockActivity()).unregisterReceiver(updateReceiver);
}
}
#Override
public void refresh(){
loadPolicy();
}
public class UpdateReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
loadPolicy();
}
}
}
Things I tried
*Saving the HTML to the assets folder by manually copy and pasting it there and then load the saved HTML works fine. But why cant I load it from the web?
Do like this
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
and then set webview client with your web view like this
web.setWebViewClient(new HelloWebViewClient());

Categories

Resources