Example usage for android.webkit WebView loadDataWithBaseURL

List of usage examples for android.webkit WebView loadDataWithBaseURL

Introduction

In this page you can find the example usage for android.webkit WebView loadDataWithBaseURL.

Prototype

public void loadDataWithBaseURL(@Nullable String baseUrl, String data, @Nullable String mimeType,
        @Nullable String encoding, @Nullable String historyUrl) 

Source Link

Document

Loads the given data into this WebView, using baseUrl as the base URL for the content.

Usage

From source file:com.gh4a.FileViewerActivity.java

private void fillData(boolean highlight) {
    String data = new String(EncodingUtils.fromBase64(mContent.getContent()));
    WebView webView = (WebView) findViewById(R.id.web_view);

    WebSettings s = webView.getSettings();
    s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
    s.setAllowFileAccess(true);/*from  www  .  j  a  va  2s  .c o m*/
    s.setBuiltInZoomControls(true);
    s.setLightTouchEnabled(true);
    s.setLoadsImagesAutomatically(true);
    s.setPluginsEnabled(false);
    s.setSupportZoom(true);
    s.setSupportMultipleWindows(true);
    s.setJavaScriptEnabled(true);
    s.setUseWideViewPort(true);

    webView.setWebViewClient(webViewClient);
    if (FileUtils.isImage(mName)) {
        String htmlImage = StringUtils.highlightImage(
                "https://github.com/" + mRepoOwner + "/" + mRepoName + "/raw/" + mRef + "/" + mPath);
        webView.loadDataWithBaseURL("file:///android_asset/", htmlImage, "text/html", "utf-8", "");
    } else {
        String highlighted = StringUtils.highlightSyntax(data, highlight, mName);
        webView.loadDataWithBaseURL("file:///android_asset/", highlighted, "text/html", "utf-8", "");
    }
}

From source file:org.mozilla.focus.browser.LocalizedContent.java

/**
 * Load the content for focus:rights/*from w  w w . j  ava 2s . c  om*/
 */
private static void loadRights(@NonNull final WebView webView) {
    final Context context = webView.getContext();
    final Resources resources = Locales.getLocalizedResources(context);

    final Map<String, String> substitutionMap = new ArrayMap<>();

    final String appName = context.getResources().getString(R.string.app_name);
    final String mplUrl = "https://www.mozilla.org/en-US/MPL/";
    final String trademarkPolicyUrl = "https://www.mozilla.org/foundation/trademarks/policy/";
    final String gplUrl = "gpl.html";
    final String trackingProtectionUrl = "https://wiki.mozilla.org/Security/Tracking_protection#Lists";
    final String licensesUrl = "licenses.html";

    final String content1 = resources.getString(R.string.your_rights_content1, appName);
    substitutionMap.put("%your-rights-content1%", content1);

    final String content2 = resources.getString(R.string.your_rights_content2, appName, mplUrl);
    substitutionMap.put("%your-rights-content2%", content2);

    final String content3 = resources.getString(R.string.your_rights_content3, appName, trademarkPolicyUrl);
    substitutionMap.put("%your-rights-content3%", content3);

    final String content4 = resources.getString(R.string.your_rights_content4, appName, licensesUrl);
    substitutionMap.put("%your-rights-content4%", content4);

    final String content5 = resources.getString(R.string.your_rights_content5, appName, gplUrl,
            trackingProtectionUrl);
    substitutionMap.put("%your-rights-content5%", content5);

    putLayoutDirectionIntoMap(webView, substitutionMap);

    final String data = HtmlLoader.loadResourceFile(context, R.raw.rights, substitutionMap);
    // We use a file:/// base URL so that we have the right origin to load file:/// css and image resources.
    webView.loadDataWithBaseURL("file:///android_asset/rights.html", data, "text/html", "UTF-8", null);
}

From source file:org.wso2.cdm.agent.AuthenticationActivity.java

public void showAgreement(String message, String title) {
    final Dialog dialog = new Dialog(context);
    dialog.setContentView(R.layout.custom_terms_popup);
    dialog.setTitle(CommonUtilities.EULA_TITLE);
    dialog.setCancelable(false);//  w  ww . j av a 2s  . co  m

    WebView web = (WebView) dialog.findViewById(R.id.webview);
    String html = "<html><body>" + message + "</body></html>";
    String mime = "text/html";
    String encoding = "utf-8";
    web.loadDataWithBaseURL(null, html, mime, encoding, null);

    Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
    Button cancelButton = (Button) dialog.findViewById(R.id.dialogButtonCancel);

    dialogButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Preference.put(context, getResources().getString(R.string.shared_pref_isagreed), "1");
            dialog.dismiss();
            loadPincodeAcitvity();
        }
    });

    cancelButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
            cancelEntry();
        }
    });

    dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_SEARCH && event.getRepeatCount() == 0) {
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                return true;
            }
            return false;
        }
    });

    dialog.show();
}

From source file:justforcommunity.radiocom.fragments.HomePageFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_home, container, false);

    mActivity = (Home) getActivity();//  w  ww  . j ava 2  s  .c  o m
    mContext = getContext();

    try {
        station.getHistory().replace("<body",
                "<body style=\'text-align:justify;color:gray;background-color:black;\'");
        station.getHistory().replaceAll("style=\".+?\"", "");

    } catch (Exception e) {

    }

    WebView wb = (WebView) v.findViewById(R.id.history_frame);
    wb.setBackgroundColor(Color.WHITE);

    // String fontscript = "<style>@font-face {font-family : 'HelveticaNeue-Light';src:url('file:///android_asset/fonts/"+VariablesGlobalesActivity.GENERICFONT+"');}</style>";
    String fontscript = "";
    String script = "<style type='text/css' >p{width:100%;}img{width:100%;height:auto;-webkit-transform: translate3d(0px,0px,0px);}a,h1,h2,h3,h4,h5,h6{color:"
            + GlobalValues.colorHTML
            + ";}div,p,span,a {max-width: 100%;}iframe{width:100%;height:auto;}</style>";

    wb.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
    });

    wb.loadDataWithBaseURL("",
            "<html><head>" + fontscript + script + "</head><body style=\"font-family:HelveticaNeue-Light; \">"
                    + station.getHistory() + "</body></html>",
            "text/html", "utf-8", "");

    wb.getSettings().setDomStorageEnabled(true);
    wb.getSettings().setJavaScriptEnabled(true);

    App application = (App) getActivity().getApplication();
    Tracker mTracker = application.getDefaultTracker();
    mTracker.setScreenName(getString(R.string.home_view));
    mTracker.send(new HitBuilders.ScreenViewBuilder().build());

    return v;
}

From source file:com.agustinprats.myhrv.fragment.MonitorFragment.java

/** Displays help to the user. */
private void showHelp() {

    AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
    alert.setTitle(getActivity().getString(R.string.Help));

    WebView wv = new WebView(getActivity());

    // loading the html file
    String htmlData = readAsset("help.html");

    // selecting the css based on the activity theme
    //        htmlData = htmlData.replaceFirst("CSS_FILE_NAME", ((MainActivity) getActivity()).isLightTheme() ? "light" : "dark");
    htmlData = htmlData.replaceFirst("CSS_FILE_NAME", "dark");
    // loading html in the webview
    wv.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "UTF-8", null);

    wv.setWebViewClient(new WebViewClient() {
        @Override//from www . j a  v  a2 s.co  m
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });

    alert.setView(wv);
    alert.setNegativeButton(getActivity().getString(R.string.Close), new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });
    alert.show();
}

From source file:com.facebook.react.views.webview.ReactWebViewManager.java

@ReactProp(name = "source")
public void setSource(WebView view, @Nullable ReadableMap source) {
    if (source != null) {
        if (source.hasKey("html")) {
            String html = source.getString("html");
            if (source.hasKey("baseUrl")) {
                view.loadDataWithBaseURL(source.getString("baseUrl"), html, HTML_MIME_TYPE, HTML_ENCODING,
                        null);/*from   ww  w  .j a  v a  2s.  c  o  m*/
            } else {
                view.loadData(html, HTML_MIME_TYPE, HTML_ENCODING);
            }
            return;
        }
        if (source.hasKey("uri")) {
            String url = source.getString("uri");
            String previousUrl = view.getUrl();
            if (previousUrl != null && previousUrl.equals(url)) {
                return;
            }
            if (source.hasKey("method")) {
                String method = source.getString("method");
                if (method.equals(HTTP_METHOD_POST)) {
                    byte[] postData = null;
                    if (source.hasKey("body")) {
                        String body = source.getString("body");
                        try {
                            postData = body.getBytes("UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            postData = body.getBytes();
                        }
                    }
                    if (postData == null) {
                        postData = new byte[0];
                    }
                    view.postUrl(url, postData);
                    return;
                }
            }
            HashMap<String, String> headerMap = new HashMap<>();
            if (source.hasKey("headers")) {
                ReadableMap headers = source.getMap("headers");
                ReadableMapKeySetIterator iter = headers.keySetIterator();
                while (iter.hasNextKey()) {
                    String key = iter.nextKey();
                    if ("user-agent".equals(key.toLowerCase(Locale.ENGLISH))) {
                        if (view.getSettings() != null) {
                            view.getSettings().setUserAgentString(headers.getString(key));
                        }
                    } else {
                        headerMap.put(key, headers.getString(key));
                    }
                }
            }
            view.loadUrl(url, headerMap);
            return;
        }
    }
    view.loadUrl(BLANK_URL);
}

From source file:com.xiaoxin.apktools.view.CustomWebViewDialog.java

@NonNull
@Override//from   ww w .  j a  v  a2s .  c  o m
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final View customView;
    try {
        customView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_webview, null);
    } catch (InflateException e) {
        throw new IllegalStateException("This device does not support Web Views.");
    }

    String dialogTitle = getArguments().getString("dialogTitle");
    AlertDialog dialog = new AlertDialog.Builder(getActivity()).setTitle(dialogTitle).setView(customView)
            .setPositiveButton(android.R.string.ok, null).show();

    final WebView webView = (WebView) customView.findViewById(R.id.webview);
    webView.getSettings().setDefaultTextEncodingName("utf-8");
    try {
        String htmlFileName = getArguments().getString("htmlFileName");
        StringBuilder buf = new StringBuilder();
        InputStream json = getActivity().getAssets().open(htmlFileName);
        BufferedReader in = new BufferedReader(new InputStreamReader(json, "UTF-8"));
        String str;
        while ((str = in.readLine()) != null)
            buf.append(str);
        in.close();

        final int accentColor = getArguments().getInt("accentColor");
        String formatLodString = buf.toString()
                .replace("{style-placeholder}", "body { background-color: #ffffff; color: #000; }")
                .replace("{link-color}", colorToHex(shiftColor(accentColor, true)))
                .replace("{link-color-active}", colorToHex(accentColor));
        webView.loadDataWithBaseURL(null, formatLodString, "text/html", "UTF-8", null);
    } catch (Throwable e) {
        webView.loadData("<h1>Unable to load</h1><p>" + e.getLocalizedMessage() + "</p>", "text/html", "UTF-8");
    }
    return dialog;
}

From source file:org.wso2.emm.agent.AuthenticationActivity.java

/**
 * Show the license text retrieved from the server.
 *
 * @param message Message text to be shown as the license.
 * @param title   Title of the license./*from   ww w  . ja v  a2  s  . co  m*/
 */
private void showAgreement(final String message, String title) {
    AuthenticationActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.custom_terms_popup);
            dialog.setTitle(Constants.EULA_TITLE);
            dialog.setCancelable(false);

            WebView webView = (WebView) dialog.findViewById(R.id.webview);

            webView.loadDataWithBaseURL(null, message, Constants.MIME_TYPE, Constants.ENCODING_METHOD, null);

            Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
            Button cancelButton = (Button) dialog.findViewById(R.id.dialogButtonCancel);

            dialogButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Preference.putBoolean(context, Constants.PreferenceFlag.IS_AGREED, true);
                    dialog.dismiss();
                    //load the next intent based on ownership type
                    checkManifestPermissions();
                }
            });

            cancelButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    CommonUtils.clearClientCredentials(context);
                    cancelEntry();
                }
            });

            dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_SEARCH
                            && event.getRepeatCount() == Constants.DEFAILT_REPEAT_COUNT) {
                        return true;
                    } else if (keyCode == KeyEvent.KEYCODE_BACK
                            && event.getRepeatCount() == Constants.DEFAILT_REPEAT_COUNT) {
                        return true;
                    }
                    return false;
                }
            });

            dialog.show();
        }
    });
}

From source file:org.mozilla.focus.webkit.FocusWebViewClient.java

private void loadAbout(final WebView webView) {
    final Resources resources = webView.getContext().getResources();

    final Map<String, String> substitutionMap = new ArrayMap<>();
    final String appName = webView.getContext().getResources().getString(R.string.app_name);
    final String learnMoreURL = SupportUtils.getManifestoURL();

    final String aboutContent = resources.getString(R.string.about_content, appName, learnMoreURL);
    substitutionMap.put("%about-content%", aboutContent);

    final String wordmark = HtmlLoader.loadPngAsDataURI(webView.getContext(), R.drawable.wordmark);
    substitutionMap.put("%wordmark%", wordmark);

    final String data = HtmlLoader.loadResourceFile(webView.getContext(), R.raw.about, substitutionMap);
    // We use a file:/// base URL so that we have the right origin to load file:/// css and
    // image resources.
    webView.loadDataWithBaseURL("file:///android_res/raw/about.html", data, "text/html", "UTF-8", null);
}

From source file:name.gudong.translate.widget.WebDialog.java

@NonNull
@Override/*ww  w .j  av a  2  s.c o m*/
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final View customView;
    try {
        customView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_about_dialog, null);
    } catch (InflateException e) {
        throw new IllegalStateException("This device does not support Web Views.");
    }

    String dialogTitle = getArguments().getString("dialogTitle");
    String neutralText = getArguments().getString("neutralText");
    String positiveText = getArguments().getString("positiveText");
    neutralText = TextUtils.isEmpty(neutralText) ? "" : neutralText;
    positiveText = TextUtils.isEmpty(neutralText) ? getString(android.R.string.ok) : positiveText;
    AlertDialog dialog = new AlertDialog.Builder(getActivity()).setTitle(dialogTitle).setView(customView)
            .setNeutralButton(neutralText, mNeutralClickCallback)
            .setPositiveButton(positiveText, mPositiveClickCallback).show();

    final WebView webView = (WebView) customView.findViewById(R.id.webview);
    webView.getSettings().setDefaultTextEncodingName("utf-8");
    try {
        String htmlFileName = getArguments().getString("htmlFileName");
        StringBuilder buf = new StringBuilder();
        InputStream json = getActivity().getAssets().open(htmlFileName);
        BufferedReader in = new BufferedReader(new InputStreamReader(json, "UTF-8"));
        String str;
        while ((str = in.readLine()) != null)
            buf.append(str);
        in.close();

        final int accentColor = getArguments().getInt("accentColor");
        String formatLodString = buf.toString()
                .replace("{style-placeholder}", "body { background-color: #ffffff; color: #000; }")
                .replace("{link-color}", colorToHex(shiftColor(accentColor, true)))
                .replace("{link-color-active}", colorToHex(accentColor));
        webView.loadDataWithBaseURL(null, formatLodString, "text/html", "UTF-8", null);
    } catch (Throwable e) {
        webView.loadData("<h1>Unable to load</h1><p>" + e.getLocalizedMessage() + "</p>", "text/html", "UTF-8");
    }
    return dialog;
}