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.gudong.appkit.ui.fragment.CustomWebViewDialog.java

@NonNull
@Override/*from w ww.j  a  v  a  2  s .com*/
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");
    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;
}

From source file:com.yang.bruce.mumuxi.util.WebDialog.java

@NonNull
@Override/*from w  w w. j  a  v  a  2s  . 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);
    setWebView(webView, customView.getContext());
    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:com.github.colorchief.colorchief.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    final TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
    tabHost.setup();/*  w  w  w .j av a  2s.c  om*/

    final TabHost.TabSpec tabImageView = tabHost.newTabSpec("Image View");
    final TabHost.TabSpec tabSettings = tabHost.newTabSpec("Settings");
    final TabHost.TabSpec tabAbout = tabHost.newTabSpec("About");

    tabImageView.setIndicator("", ContextCompat.getDrawable(this, R.drawable.ic_action_picture));
    tabImageView.setContent(R.id.tabImageView);

    tabSettings.setIndicator("", ContextCompat.getDrawable(this, R.drawable.ic_action_gear));
    tabSettings.setContent(R.id.tabSettings);

    tabAbout.setIndicator("", ContextCompat.getDrawable(this, R.drawable.ic_action_help));
    tabAbout.setContent(R.id.tabAbout);

    /** Add the tabs  to the TabHost to display. */
    tabHost.addTab(tabImageView);
    tabHost.addTab(tabSettings);
    tabHost.addTab(tabAbout);

    colorLUT.initLUT(LUT_SIZE, LUT_SIZE, LUT_SIZE);

    //check savedInstance
    // for Tab state and set active tab accordingly
    // for LUT values and update (restore) accordingly
    if (savedInstanceState != null) {
        tabHost.setCurrentTab(savedInstanceState.getInt("Active Tab"));
        colorLUT.setColorLutArray(savedInstanceState.getIntArray("Color LUT"));
    }

    ((SeekBar) findViewById(R.id.seekBarChromaPowerFactor)).setMax(POWER_FACTOR_SEEK_BAR_MAX);
    ((SeekBar) findViewById(R.id.seekBarChromaPowerFactor)).setProgress(getSeekPosition(powerFactor));

    if (Lselect == LutCalculate.L_SELECT_IN) {
        ((RadioButton) findViewById(R.id.radioButtonLin)).setChecked(true);
        ((RadioButton) findViewById(R.id.radioButtonLout)).setChecked(false);
    } else if (Lselect == LutCalculate.L_SELECT_OUT) {
        ((RadioButton) findViewById(R.id.radioButtonLin)).setChecked(false);
        ((RadioButton) findViewById(R.id.radioButtonLout)).setChecked(true);
    }
    if (Cselect == LutCalculate.C_SELECT_ABSOLUTE) {
        ((RadioButton) findViewById(R.id.radioButtonCin)).setChecked(true);
        ((RadioButton) findViewById(R.id.radioButtonCrelative)).setChecked(false);
        ((SeekBar) findViewById(R.id.seekBarChromaPowerFactor)).setEnabled(false);

    } else if (Cselect == LutCalculate.C_SELECT_RELATIVE) {
        ((RadioButton) findViewById(R.id.radioButtonCin)).setChecked(false);
        ((RadioButton) findViewById(R.id.radioButtonCrelative)).setChecked(true);
        ((SeekBar) findViewById(R.id.seekBarChromaPowerFactor)).setEnabled(true);
    }

    if (uriIccProfileIn != null)
        iccProfileIn.loadFromFile(uriIccProfileIn);
    if (uriIccProfileOut != null)
        iccProfileOut.loadFromFile(uriIccProfileOut);

    if (bitmapLoaded) {

        transformImage();
        updateImageViewer();

    } else {
        ((ImageView) findViewById(R.id.imageView)).setImageBitmap(
                BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_folder_open_blue));

    }

    ((ImageView) findViewById(R.id.imageView)).addOnLayoutChangeListener(new View.OnLayoutChangeListener() {

        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop,
                int oldRight, int oldBottom) {
            // if layout is not complete we will get all zero values for the positions, so ignore the event
            if (left == 0 && top == 0 && right == 0 && bottom == 0) {
                return;
            } else {
                if (bitmapLoaded) {
                    try {
                        decodeImageUri(uriBitmapOriginal, (ImageView) findViewById(R.id.imageView));
                    } catch (FileNotFoundException e) {
                        Log.e(TAG, "Failed to grab Bitmap: " + e);
                    }
                    //if (iccProfileOut.isValidProfile() && iccProfileIn.isValidProfile())
                    transformImage();
                    updateImageViewer();

                }
            }

        }
    });

    ((SeekBar) findViewById(R.id.seekBarChromaPowerFactor))
            .setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    powerFactor = getPowerFactor(seekBar.getProgress());
                    //convertImage(seekBar);
                    //updateImageViewer();
                }
            });

    //when switching tabs, make sure:
    //a: update the image when switching to the imageview tab in case any settings changes were made
    //b: hide the color controls overlay if we are not on the imageview tab
    tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
        @Override
        public void onTabChanged(String tabId) {
            if (tabId.equals(tabImageView.getTag())) {
                //Log.d(TAG,"Tab changed to image view");

                if (iccProfileIn.isValidProfile() && iccProfileOut.isValidProfile() && bitmapLoaded) {
                    recalculateTransform();
                    transformImage();
                    updateImageViewer();
                }
            } else if (tabId.equals(tabAbout.getTag())) {
                ((LinearLayout) findViewById(R.id.overlayColorControl)).setVisibility(View.INVISIBLE);
                InputStream inputStream = getResources().openRawResource(R.raw.about);
                ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
                try {
                    int bytesRead = inputStream.read();
                    while (bytesRead != -1) {
                        byteArrayStream.write(bytesRead);
                        bytesRead = inputStream.read();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //TextView textViewAbout = (TextView) findViewById(R.id.textViewAbout);
                //textViewAbout.setText(Html.fromHtml(byteArrayStream.toString()));
                WebView webViewAbout = (WebView) findViewById(R.id.webViewAbout);
                webViewAbout.loadDataWithBaseURL(null, byteArrayStream.toString(), "text/html", "utf-8", null);
            } else {
                ((LinearLayout) findViewById(R.id.overlayColorControl)).setVisibility(View.INVISIBLE);
            }
        }
    });

}

From source file:info.staticfree.android.units.Units.java

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_ABOUT: {
        final Builder builder = new AlertDialog.Builder(this);

        builder.setTitle(R.string.dialog_about_title);
        builder.setIcon(R.drawable.icon);

        try {//  ww  w . ja  v  a 2s.  com
            final WebView wv = new WebView(this);
            final InputStream is = getAssets().open("README.xhtml");
            wv.loadDataWithBaseURL("file:///android_asset/", inputStreamToString(is), "application/xhtml+xml",
                    "utf-8", null);
            wv.setBackgroundColor(0);
            builder.setView(wv);
        } catch (final IOException e) {
            builder.setMessage(R.string.err_no_load_about);
            e.printStackTrace();
        }

        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                setResult(RESULT_OK);
            }
        });
        return builder.create();
    }

    case DIALOG_ALL_UNITS: {
        final Builder b = new Builder(Units.this);
        b.setTitle(R.string.dialog_all_units_title);
        final ExpandableListView unitExpandList = new ExpandableListView(Units.this);
        unitExpandList.setId(android.R.id.list);
        final String[] groupProjection = { UsageEntry._ID, UsageEntry._UNIT, UsageEntry._FACTOR_FPRINT };
        // any selection below will select from the grouping description
        final Cursor cursor = managedQuery(UsageEntry.CONTENT_URI_CONFORM_TOP, groupProjection, null, null,
                UnitUsageDBHelper.USAGE_SORT);

        unitExpandList.setAdapter(new UnitsExpandableListAdapter(cursor, this,
                android.R.layout.simple_expandable_list_item_1, android.R.layout.simple_expandable_list_item_1,
                new String[] { UsageEntry._UNIT }, new int[] { android.R.id.text1 },
                new String[] { UsageEntry._UNIT }, new int[] { android.R.id.text1 }));
        unitExpandList.setCacheColorHint(0);
        unitExpandList.setOnChildClickListener(allUnitChildClickListener);
        b.setView(unitExpandList);
        return b.create();
    }

    case DIALOG_UNIT_CATEGORY: {
        final Builder b = new Builder(new ContextThemeWrapper(this, android.R.style.Theme_Black));
        final String[] from = { UsageEntry._UNIT };
        final int[] to = { android.R.id.text1 };
        b.setTitle("all units");
        final String[] projection = { UsageEntry._ID, UsageEntry._UNIT, UsageEntry._FACTOR_FPRINT };
        final Cursor c = managedQuery(UsageEntry.CONTENT_URI, projection, null, null,
                UnitUsageDBHelper.USAGE_SORT);
        dialogUnitCategoryList = new SimpleCursorAdapter(this, android.R.layout.select_dialog_item, c, from,
                to);
        b.setAdapter(dialogUnitCategoryList, dialogUnitCategoryOnClickListener);

        return b.create();
    }

    case DIALOG_LOADING_UNITS: {
        final ProgressDialog pd = new ProgressDialog(this);
        pd.setIndeterminate(true);
        pd.setTitle(R.string.app_name);
        pd.setMessage(getText(R.string.dialog_loading_units));
        return pd;
    }

    default:
        throw new IllegalArgumentException("Unknown dialog ID:" + id);
    }
}

From source file:im.neon.adapters.VectorMediasViewerAdapter.java

/**
 * Update the image page.//from   w ww.  java  2 s . co  m
 * @param webView the image is rendered in a webview.
 * @param imageUri the image Uri.
 * @param viewportContent  the viewport.
 * @param css the css.
 */
private void loadImage(WebView webView, Uri imageUri, String viewportContent, String css) {
    String html = "<html><head><meta name='viewport' content='" + viewportContent + "'/>"
            + "<style type='text/css'>" + css + "</style></head>" + "<body> <div class='wrap'>" + "<img "
            + ("src='" + imageUri.toString() + "'") + " onerror='this.style.display=\"none\"' id='image' "
            + viewportContent + "/>" + "</div>" + "</body>" + "</html>";

    String mime = "text/html";
    String encoding = "utf-8";

    webView.loadDataWithBaseURL(null, html, mime, encoding, null);
    webView.requestLayout();
}

From source file:org.wso2.iot.agent.activities.AuthenticationActivity.java

/**
 * Show the license text retrieved from the server.
 *
 * @param licenseText Message text to be shown as the license.
 * @param title   Title of the license./* www .  java 2s .  c o m*/
 */
private void showAgreement(final String licenseText, final String title) {
    AuthenticationActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            final Dialog dialog = new Dialog(context, R.style.Dialog);
            dialog.setContentView(R.layout.dialog_license);
            dialog.setCancelable(false);

            WebView webView = (WebView) dialog.findViewById(R.id.webViewLicense);
            webView.loadDataWithBaseURL(null, licenseText, Constants.MIME_TYPE, Constants.ENCODING_METHOD,
                    null);

            TextView textViewTitle = (TextView) dialog.findViewById(R.id.textViewDeviceNameTitle);
            textViewTitle.setText(title);

            Button btnAgree = (Button) dialog.findViewById(R.id.dialogButtonOK);
            Button btnCancel = (Button) dialog.findViewById(R.id.dialogButtonCancel);

            btnAgree.setOnClickListener(new OnClickListener() {
                @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void onClick(View v) {
                    Preference.putBoolean(context, Constants.PreferenceFlag.IS_AGREED, true);
                    dialog.dismiss();
                    //load the next intent based on ownership type
                    startDeviceAdminPrompt();
                }
            });

            btnCancel.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.DEFAULT_REPEAT_COUNT) {
                        return true;
                    } else if (keyCode == KeyEvent.KEYCODE_BACK
                            && event.getRepeatCount() == Constants.DEFAULT_REPEAT_COUNT) {
                        return true;
                    }
                    return false;
                }
            });

            dialog.show();
        }
    });
}

From source file:com.near.chimerarevo.fragments.PostFragment.java

@SuppressLint("SetJavaScriptEnabled")
private void addWebObject(String width, String height, String url) {
    WebView wv = new WebView(getActivity());
    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

    wv.setLayoutParams(params);//from  ww  w .  j  a va  2 s . c o m
    wv.getSettings().setUseWideViewPort(true);
    wv.getSettings().setLoadWithOverviewMode(true);
    wv.getSettings().setSupportZoom(false);
    wv.setVerticalScrollBarEnabled(true);
    wv.setHorizontalScrollBarEnabled(true);
    wv.getSettings().setJavaScriptEnabled(true);
    wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    wv.setWebViewClient(new WebViewClient());

    String frame = "<iframe width=\"" + width + "\" height=\"" + height + "\" frameborder=\"0\" src=\"" + url
            + "\"/>";
    wv.loadDataWithBaseURL(url, frame, "html/plain", "UTF-8", null);
    lay.addView(wv);
}

From source file:com.github.akinaru.hcidebugger.activity.DescriptionActivity.java

protected void onCreate(Bundle savedInstanceState) {

    setLayout(R.layout.description_activity);
    super.onCreate(savedInstanceState);

    //setup navigation items
    setupDrawerContent(nvDrawer);/* w  w  w  .  j av a  2s  .c o  m*/

    //hide max packet count for this activity
    nvDrawer.getMenu().findItem(R.id.set_max_packet_num).setVisible(false);
    nvDrawer.getMenu().findItem(R.id.browse_file).setVisible(false);
    nvDrawer.getMenu().findItem(R.id.change_settings).setVisible(false);

    //get information sent via intent to be displayed
    String hciPacket = getIntent().getExtras().getString(Constants.INTENT_HCI_PACKET);
    String snoopPacket = getIntent().getExtras().getString(Constants.INTENT_SNOOP_PACKET);
    int packetNumber = getIntent().getExtras().getInt(Constants.INTENT_PACKET_NUMBER);
    String ts = getIntent().getExtras().getString(Constants.INTENT_PACKET_TS);
    String packet_type = getIntent().getExtras().getString(Constants.INTENT_PACKET_TYPE);
    String destination = getIntent().getExtras().getString(Constants.INTENT_PACKET_DEST);

    //setup description item table
    tablelayout = (TableLayout) findViewById(R.id.tablelayout);
    altTableRow(2);

    //setup json highlishter web page
    WebView lWebView = (WebView) findViewById(R.id.webView);

    TextView number_value = (TextView) findViewById(R.id.number_value);
    TextView ts_value = (TextView) findViewById(R.id.ts_value);
    TextView packet_type_value = (TextView) findViewById(R.id.packet_type_value);
    TextView destination_value = (TextView) findViewById(R.id.dest_value);
    number_value.setText("" + packetNumber);
    ts_value.setText(ts);
    packet_type_value.setText(packet_type);
    destination_value.setText(destination);

    WebSettings webSettings = lWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    int spacesToIndentEachLevel = 2;
    String beautify = "{}";
    try {
        beautify = new JSONObject(hciPacket).toString(spacesToIndentEachLevel);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    String html = "<HTML><HEAD><link rel=\"stylesheet\" href=\"styles.css\">"
            + "<script src=\"highlight.js\"></script>" + "<script>hljs.initHighlightingOnLoad();</script>"
            + "</HEAD><body>" + "<pre><code class=\"json\">" + beautify + "</code></pre>" + "</body></HTML>";

    lWebView.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", null);
}

From source file:com.github.longkai.zhihu.ui.AnswerActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.answer);/*  w ww .  j  ava2s . c o  m*/

    final TextView title = (TextView) findViewById(android.R.id.title);
    final WebView desc = (WebView) findViewById(R.id.description);
    final TextView nick = (TextView) findViewById(R.id.nick);
    final ImageView avatar = (ImageView) findViewById(R.id.avatar);
    final TextView status = (TextView) findViewById(R.id.status);
    final WebView answer = (WebView) findViewById(R.id.content);
    final TextView last_alter_date = (TextView) findViewById(R.id.last_alter_date);

    id = getIntent().getLongExtra(ANSWER_ID, 0);
    new AsyncQueryHandler(getContentResolver()) {
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            if (cursor.moveToNext()) {
                // 
                aid = cursor.getLong(cursor.getColumnIndex(ANSWER_ID));
                qid = cursor.getLong(cursor.getColumnIndex(QUESTION_ID));
                questionTitle = cursor.getString(cursor.getColumnIndex(TITLE));
                title.setText(questionTitle);
                String description = cursor.getString(cursor.getColumnIndex(DESCRIPTION));
                if (TextUtils.isEmpty(description)) {
                    desc.setVisibility(View.GONE);
                } else {
                    desc.loadDataWithBaseURL(null, description, "text/html", "utf-8", null);
                    desc.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
                    desc.setBackgroundColor(getResources().getColor(R.color.bgcolor));
                }

                // 
                uid = cursor.getString(cursor.getColumnIndex(UID));
                nick.setText(cursor.getString(cursor.getColumnIndex(NICK)));
                String src = cursor.getString(cursor.getColumnIndex(AVATAR));
                ZhihuApp.getImageLoader().get(src,
                        ImageLoader.getImageListener(avatar, R.drawable.ic_launcher, R.drawable.ic_launcher));
                status.setText(cursor.getString(cursor.getColumnIndex(STATUS)));

                // 
                String content = cursor.getString(cursor.getColumnIndex(ANSWER));
                answerDigest = content.length() > 50 ? content.substring(0, 50) : content;
                answer.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
                answer.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
                answer.setBackgroundColor(getResources().getColor(R.color.bgcolor));

                last_alter_date.setText(DateUtils
                        .getRelativeTimeSpanString(cursor.getLong(cursor.getColumnIndex(LAST_ALTER_DATE))));

                cursor.close();
            }
        }
    }.startQuery(0, null, Uri.parse(ZhihuProvider.BASE_URI + Constants.ITEMS + "/" + id), ITEM_PROJECTION, null,
            null, null);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

From source file:nirwan.cordova.plugin.printer.Printer.java

private void loadContentAsBitmapIntoPrintController(String content, final Intent intent) {
    Activity ctx = cordova.getActivity();
    final WebView page = new WebView(ctx);
    final Printer self = this;

    page.setVisibility(View.INVISIBLE);
    page.getSettings().setJavaScriptEnabled(false);

    page.setWebViewClient(new WebViewClient() {
        @Override//from   www  .jav a2  s .c o m
        public void onPageFinished(final WebView page, String url) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Bitmap screenshot = self.takeScreenshot(page);
                    File tmpFile = self.saveScreenshotToTmpFile(screenshot);
                    ViewGroup vg = (ViewGroup) (page.getParent());

                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tmpFile));

                    vg.removeView(page);
                }
            }, 1000);
        }
    });

    //Set base URI to the assets/www folder
    String baseURL = webView.getUrl();
    baseURL = baseURL.substring(0, baseURL.lastIndexOf('/') + 1);

    ctx.addContentView(page, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    page.loadDataWithBaseURL(baseURL, content, "text/html", "UTF-8", null);
}