Example usage for android.webkit WebView loadData

List of usage examples for android.webkit WebView loadData

Introduction

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

Prototype

public void loadData(String data, @Nullable String mimeType, @Nullable String encoding) 

Source Link

Document

Loads the given data into this WebView using a 'data' scheme URL.

Usage

From source file:com.radiusnetworks.museumguide.MuseumItemFragment.java

public void showItem(String currentItemId) {
    itemId = currentItemId;//from  ww  w.j  a v a 2s  .c  o  m
    if (rootView != null) {
        Log.d(TAG, "Setting up fragment with " + "item" + currentItemId);
        WebView webview = (WebView) rootView.findViewById(R.id.webView);
        RemoteAssetCache assetCache = new RemoteAssetCache(this.getActivity());
        String html = assetCache.getHtmlContentByName("item" + currentItemId + "_html");
        ImageView imageView2 = assetCache.getImageByName("item" + currentItemId);
        if (imageView2 != null) {
            ImageView imageView = (ImageView) rootView.findViewById(R.id.museumItemImage);
            imageView.setImageDrawable(imageView2.getDrawable());
        }
        if (html != null) {
            webview.loadData(html, "text/html", null);
        }
        rootView.findViewById(R.id.nextButton).setVisibility(View.INVISIBLE);
    }
}

From source file:com.kentph.ttcnextbus.NetworkActivity.java

private void showErrorPage() {
    setContentView(R.layout.activity_network);

    // The specified network connection is not available. Displays error message.
    WebView myWebView = (WebView) findViewById(R.id.webview);
    myWebView.loadData(getResources().getString(R.string.connection_error), "text/html", null);
    //        TextView textView = (TextView) findViewById(R.id.text);
    //        textView.setText(getResources().getString(R.string.connection_error));
}

From source file:org.jorge.cmp.ui.fragment.ArticleReaderFragment.java

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    setHasOptionsMenu(Boolean.TRUE);
    final View ret = inflater.inflate(R.layout.fragment_article_reader, container, Boolean.FALSE);
    View mHeaderView = ret.findViewById(R.id.image);
    PicassoUtils.loadInto(mContext, mArticle.getImageUrl(), mDefaultImageId,
            (android.widget.ImageView) mHeaderView, TAG);
    final String title = mArticle.getTitle();
    mHeaderView.setContentDescription(title);
    ((TextView) ret.findViewById(R.id.title)).setText(title);
    WebView contentView = (WebView) ret.findViewById(android.R.id.text1);
    WebSettings webViewSettings = contentView.getSettings();
    contentView.setOverScrollMode(View.OVER_SCROLL_NEVER);
    webViewSettings.setJavaScriptCanOpenWindowsAutomatically(Boolean.TRUE);
    webViewSettings.setBuiltInZoomControls(Boolean.FALSE);
    contentView.setBackgroundColor(0x00000000); //I wonder why the default background is white
    contentView.loadData(mArticle.getPreviewText(), "text/html; charset=UTF-8", "UTF-8");

    mActionBar = mActivity.getSupportActionBar();
    mActionBar.setDisplayHomeAsUpEnabled(Boolean.TRUE);
    mActionBarBackgroundDrawable = new ColorDrawable(
            mContext.getResources().getColor(R.color.toolbar_background));
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        mActionBarBackgroundDrawable.setCallback(mDrawableCallback);
    }/*w  ww. j a v  a 2s  .c om*/
    mActionBar.setBackgroundDrawable(mActionBarBackgroundDrawable);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mOriginalElevation = mActionBar.getElevation();
        mActionBar.setElevation(0); //So that the shadow of the ActionBar doesn't show over
        // the article title
    }
    mActionBar.setTitle(mActivity.getString(R.string.section_title_article_reader));

    StickyParallaxNotifyingScrollView scrollView = (StickyParallaxNotifyingScrollView) ret
            .findViewById(R.id.scroll_view);
    scrollView.setOnScrollChangedListener(mOnScrollChangedListener);
    scrollView.smoothScrollTo(0, 0);

    if (!mArticle.isRead()) {
        mMarkAsReadFab = (FloatingActionButton) ret.findViewById(R.id.fab_button_mark_as_read);
        mMarkAsReadFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                markArticleAsRead(mArticle);
                if (mMarkAsReadFab.isShown())
                    mMarkAsReadFab.hide();
            }

            private void markArticleAsRead(FeedArticle article) {
                final Realm r = Realm.getInstanceByRealmId(ArticleReaderFragment.this.mAccount.getRealmEnum());
                String l = PreferenceAssistant.readSharedString(mContext, PreferenceAssistant.PREF_LANG, null);
                if (l == null || !Arrays.asList(r.getLocales()).contains(l)) {
                    l = r.getLocales()[0];
                    PreferenceAssistant.writeSharedString(mContext, PreferenceAssistant.PREF_LANG, l);
                }
                final Class newsClass = NewsListFragment.class;
                final Class communityClass = CommunityListFragment.class;
                final Class schoolClass = SchoolListFragment.class;
                String tableName;
                if (mClass == newsClass) {
                    if (l == null || !Arrays.asList(r.getLocales()).contains(l)) {
                        l = r.getLocales()[0];
                        PreferenceAssistant.writeSharedString(mContext, PreferenceAssistant.PREF_LANG, l);
                    }
                    tableName = SQLiteDAO.getNewsTableName(r, l);
                } else if (mClass == communityClass) {
                    tableName = SQLiteDAO.getCommunityTableName();
                } else if (mClass == schoolClass) {
                    tableName = SQLiteDAO.getSchoolTableName();
                } else {
                    throw new IllegalArgumentException(
                            "Feed list fragment class " + mClass.getCanonicalName() + " not recognized.");
                }
                new AsyncTask<Object, Void, Void>() {
                    @Override
                    protected Void doInBackground(Object... params) {
                        SQLiteDAO.getInstance().markArticleAsRead((FeedArticle) params[0], (String) params[1]);
                        return null;
                    }
                }.executeOnExecutor(Executors.newSingleThreadExecutor(), article, tableName);
                article.markAsRead();
            }
        });

        mMarkAsReadFab.hide();
        mMarkAsReadFab.setVisibility(View.VISIBLE);

        showMarkAsReadFabIfItProceeds();
    }
    return ret;
}

From source file:org.ciasaboark.tacere.activity.AboutLicenseActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_about_activity_license);
    // Show the Up button in the action bar.
    setupActionBar();/*from  w  w w. j  av  a2 s .com*/

    WebView wv = (WebView) findViewById(R.id.webView1);

    String htmlData = "";
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(getAssets().open("license.html")));

        String line;
        while ((line = br.readLine()) != null) {
            htmlData += line;
        }
    } catch (FileNotFoundException e) {
        Log.e(TAG, e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    }

    int colorInt = getResources().getColor(R.color.link_color);
    String hexColor = String.format("#%06X", (0xFFFFFF & colorInt));
    while (htmlData.contains("LINKCOLOR")) {
        htmlData = htmlData.replace("LINKCOLOR", hexColor);
    }

    wv.loadData(htmlData, "text/html", "UTF8");

    // All links should open in the default browser, not this WebView
    wv.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }
    });

    wv.setBackgroundColor(0x00000000);
    wv.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
}

From source file:com.userhook.view.UHMessageView.java

protected void loadWebViewContent(String html) {

    WebView webView = new WebView(getContext());
    webView.setWebViewClient(new MessageWebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);

    // find dialog width in pixels
    final float scale = getResources().getDisplayMetrics().density;
    int width = (int) (dialogWidth * scale);

    LayoutParams layoutParams = new LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT);
    layoutParams.addRule(CENTER_IN_PARENT);
    addView(webView, layoutParams);//from  w ww . j ava  2 s .  com

    webView.loadData(html, "text/html", "utf-8");
    contentView = webView;

    contentLoaded = true;
}

From source file:com.amaze.filemanager.fragments.preference_fragments.Preffrag.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PreferenceUtils.reset();//from  w  w  w  .  j a va  2 s.co m
    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.preferences);

    sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());

    final int th1 = Integer.parseInt(sharedPref.getString("theme", "0"));
    theme = th1 == 2 ? PreferenceUtils.hourOfDay() : th1;
    findPreference("donate").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            ((com.amaze.filemanager.activities.Preferences) getActivity()).donate();
            return false;
        }
    });
    findPreference("columns").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            final String[] sort = getResources().getStringArray(R.array.columns);
            MaterialDialog.Builder a = new MaterialDialog.Builder(getActivity());
            if (theme == 1)
                a.theme(Theme.DARK);
            a.title(R.string.gridcolumnno);
            int current = Integer.parseInt(sharedPref.getString("columns", "-1"));
            current = current == -1 ? 0 : current;
            if (current != 0)
                current = current - 1;
            a.items(sort).itemsCallbackSingleChoice(current, new MaterialDialog.ListCallbackSingleChoice() {
                @Override
                public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                    sharedPref.edit().putString("columns", "" + (which != 0 ? sort[which] : "" + -1)).commit();
                    dialog.dismiss();
                    return true;
                }
            });
            a.build().show();
            return true;
        }
    });

    findPreference("theme").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            String[] sort = getResources().getStringArray(R.array.theme);
            int current = Integer.parseInt(sharedPref.getString("theme", "0"));
            MaterialDialog.Builder a = new MaterialDialog.Builder(getActivity());
            if (theme == 1)
                a.theme(Theme.DARK);
            a.items(sort).itemsCallbackSingleChoice(current, new MaterialDialog.ListCallbackSingleChoice() {
                @Override
                public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                    sharedPref.edit().putString("theme", "" + which).commit();
                    dialog.dismiss();
                    restartPC(getActivity());
                    return true;
                }
            });
            a.title(R.string.theme);
            a.build().show();
            return true;
        }
    });
    findPreference("colors").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            ((com.amaze.filemanager.activities.Preferences) getActivity()).selectItem(1);
            return true;
        }
    });

    final CheckBx rootmode = (CheckBx) findPreference("rootmode");
    rootmode.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            boolean b = sharedPref.getBoolean("rootmode", false);
            if (b) {
                if (RootTools.isAccessGiven()) {
                    rootmode.setChecked(true);

                } else {
                    rootmode.setChecked(false);

                    Toast.makeText(getActivity(), getResources().getString(R.string.rootfailure),
                            Toast.LENGTH_LONG).show();
                }
            } else {
                rootmode.setChecked(false);

            }

            return false;
        }
    });

    // Authors
    Preference preference4 = (Preference) findPreference("authors");
    preference4.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {

            MaterialDialog.Builder a = new MaterialDialog.Builder(getActivity());
            skin = PreferenceUtils.getPrimaryColorString(sharedPref);
            int fab_skin = Color.parseColor(PreferenceUtils.getAccentString(sharedPref));
            if (theme == 1)
                a.theme(Theme.DARK);

            a.positiveText(R.string.close);
            a.positiveColor(fab_skin);
            LayoutInflater layoutInflater = (LayoutInflater) getActivity()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = layoutInflater.inflate(R.layout.authors, null);
            a.customView(view, true);
            a.title(R.string.authors);
            a.callback(new MaterialDialog.ButtonCallback() {
                @Override
                public void onPositive(MaterialDialog materialDialog) {

                    materialDialog.cancel();
                }

                @Override
                public void onNegative(MaterialDialog materialDialog) {

                }
            });
            /*a.setNegativeButton(R.string.close, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
            });*/
            a.build().show();

            final Intent intent = new Intent(Intent.ACTION_VIEW);

            TextView googlePlus1 = (TextView) view.findViewById(R.id.googlePlus1);
            googlePlus1.setTextColor(Color.parseColor(skin));
            TextView googlePlus2 = (TextView) view.findViewById(R.id.googlePlus2);
            googlePlus2.setTextColor(Color.parseColor(skin));
            TextView git1 = (TextView) view.findViewById(R.id.git1);
            git1.setTextColor(Color.parseColor(skin));
            TextView git2 = (TextView) view.findViewById(R.id.git2);
            git2.setTextColor(Color.parseColor(skin));

            googlePlus1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    intent.setData(Uri.parse("https://plus.google.com/u/0/110424067388738907251/"));
                    startActivity(intent);
                }
            });
            googlePlus2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    intent.setData(Uri.parse("https://plus.google.com/+VishalNehra/"));
                    startActivity(intent);
                }
            });
            git1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    intent.setData(Uri.parse("https://github.com/arpitkh96"));
                    startActivity(intent);
                }
            });
            git2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    intent.setData(Uri.parse("https://github.com/vishal0071"));
                    startActivity(intent);
                }
            });

            // icon credits
            TextView textView = (TextView) view.findViewById(R.id.icon_credits);
            textView.setMovementMethod(LinkMovementMethod.getInstance());
            textView.setLinksClickable(true);
            textView.setText(Html.fromHtml(getActivity().getString(R.string.icon_credits)));

            return false;
        }
    });

    // Changelog
    Preference preference1 = (Preference) findPreference("changelog");
    preference1.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {

            MaterialDialog.Builder a = new MaterialDialog.Builder(getActivity());
            if (theme == 1)
                a.theme(Theme.DARK);
            a.title(R.string.changelog);
            a.content(Html.fromHtml(getActivity().getString(R.string.changelog_version_9)
                    + getActivity().getString(R.string.changelog_change_9)
                    + getActivity().getString(R.string.changelog_version_8)
                    + getActivity().getString(R.string.changelog_change_8)
                    + getActivity().getString(R.string.changelog_version_7)
                    + getActivity().getString(R.string.changelog_change_7)
                    + getActivity().getString(R.string.changelog_version_6)
                    + getActivity().getString(R.string.changelog_change_6)
                    + getActivity().getString(R.string.changelog_version_5)
                    + getActivity().getString(R.string.changelog_change_5)
                    + getActivity().getString(R.string.changelog_version_4)
                    + getActivity().getString(R.string.changelog_change_4)
                    + getActivity().getString(R.string.changelog_version_3)
                    + getActivity().getString(R.string.changelog_change_3)
                    + getActivity().getString(R.string.changelog_version_2)
                    + getActivity().getString(R.string.changelog_change_2)
                    + getActivity().getString(R.string.changelog_version_1)
                    + getActivity().getString(R.string.changelog_change_1)));
            a.negativeText(R.string.close);
            a.positiveText(R.string.fullChangelog);
            int fab_skin = Color.parseColor(PreferenceUtils.getAccentString(sharedPref));
            a.positiveColor(fab_skin);
            a.negativeColor(fab_skin);
            a.callback(new MaterialDialog.ButtonCallback() {
                @Override
                public void onPositive(MaterialDialog materialDialog) {

                    Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse("https://github.com/arpitkh96/AmazeFileManager/commits/master"));
                    startActivity(intent);
                }

                @Override
                public void onNegative(MaterialDialog materialDialog) {

                    materialDialog.cancel();
                }
            }).build().show();
            return false;
        }
    });

    // Open Source Licenses
    Preference preference2 = (Preference) findPreference("os");
    //Defining dialog layout
    final Dialog dialog = new Dialog(getActivity(),
            android.R.style.Theme_Holo_Light_DialogWhenLarge_NoActionBar);
    //dialog.setTitle("Open-Source Licenses");
    LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    final View dialog_view = inflater.inflate(R.layout.open_source_licenses, null);
    dialog.setContentView(dialog_view);

    preference2.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference arg0) {

            WebView wv = (WebView) dialog_view.findViewById(R.id.webView1);
            PreferenceUtils preferenceUtils = new PreferenceUtils();
            wv.loadData(PreferenceUtils.LICENCE_TERMS, "text/html", null);
            dialog.show();
            return false;
        }
    });

    // Feedback
    Preference preference3 = (Preference) findPreference("feedback");
    preference3.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Intent emailIntent = new Intent(Intent.ACTION_SENDTO,
                    Uri.fromParts("mailto", "arpitkh96@gmail.com", null));
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Feedback : Amaze File Manager");
            Toast.makeText(getActivity(), getActivity().getFilesDir().getPath(), Toast.LENGTH_SHORT).show();
            File f = new File(getActivity().getExternalFilesDir("internal"), "log.txt");
            if (f.exists()) {
                emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
            }
            startActivity(Intent.createChooser(emailIntent, getResources().getString(R.string.feedback)));
            return false;
        }
    });

    // rate
    Preference preference5 = (Preference) findPreference("rate");
    preference5.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Intent intent1 = new Intent(Intent.ACTION_VIEW);
            intent1.setData(Uri.parse("market://details?id=com.amaze.filemanager"));
            startActivity(intent1);
            return false;
        }
    });

    // studio
    Preference studio = findPreference("studio");
    studio.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            COUNT++;
            if (COUNT >= 5) {
                if (toast != null)
                    toast.cancel();
                toast = Toast.makeText(getActivity(), "Studio Mode : " + COUNT, Toast.LENGTH_SHORT);
                toast.show();

                sharedPref.edit().putInt("studio", Integer.parseInt(Integer.toString(COUNT) + "000")).apply();
            } else {
                sharedPref.edit().putInt("studio", 0).apply();
            }
            return false;
        }
    });

    // G+
    gplus = (CheckBx) findPreference("plus_pic");
    gplus.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            if (gplus.isChecked()) {
                boolean b = checkGplusPermission();
                if (!b)
                    requestGplusPermission();
            }
            return false;
        }
    });
    if (BuildConfig.IS_VERSION_FDROID)
        gplus.setEnabled(false);

    // Colored navigation bar
}

From source file:emu.project64.GalleryActivity.java

void setWaitScreen(boolean set) {
    if (set) {/*from   w  ww .ja v  a  2 s.co m*/
        WebView webView = (WebView) findViewById(R.id.screen_wait);
        webView.loadData(Utility.readAsset("loading.htm", ""), "text/html", "UTF8");
    }
    findViewById(R.id.screen_main).setVisibility(set ? View.GONE : View.VISIBLE);
    findViewById(R.id.screen_wait).setVisibility(set ? View.VISIBLE : View.GONE);
}

From source file:org.ciasaboark.tacere.activity.fragment.AboutLicenseFragment.java

private void initViews() {
    // Show the Up button in the action bar.
    //        setupActionBar();

    WebView wv = (WebView) rootView.findViewById(R.id.webView1);

    String htmlData = "";
    try {// ww w  .j  a v a 2  s .  c o  m
        BufferedReader br = new BufferedReader(new InputStreamReader(context.getAssets().open("license.html")));

        String line;
        while ((line = br.readLine()) != null) {
            htmlData += line;
        }
    } catch (FileNotFoundException e) {
        Log.e(TAG, e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    }

    int colorInt = getResources().getColor(R.color.link_color);
    String hexColor = String.format("#%06X", (0xFFFFFF & colorInt));
    while (htmlData.contains("LINKCOLOR")) {
        htmlData = htmlData.replace("LINKCOLOR", hexColor);
    }

    wv.loadData(htmlData, "text/html", "UTF8");

    // All links should open in the default browser, not this WebView
    wv.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }
    });

    wv.setBackgroundColor(0x00000000);
    wv.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_settings:
        startActivity(new Intent(this, ZumoPreferenceActivity.class));
        return true;

    case R.id.menu_run_tests:
        if (getMobileServiceKey().trim() == "" || getMobileServiceURL().trim() == "") {
            startActivity(new Intent(this, ZumoPreferenceActivity.class));
        } else {//from w ww  .  j a  v a2s  .  c  o  m
            runTests();
        }
        return true;

    case R.id.menu_check_all:
        changeCheckAllTests(true);
        return true;

    case R.id.menu_uncheck_all:
        changeCheckAllTests(false);
        return true;

    case R.id.menu_reset:
        refreshTestGroupsAndLog();
        return true;

    case R.id.menu_view_log:
        AlertDialog.Builder logDialogBuilder = new AlertDialog.Builder(this);
        logDialogBuilder.setTitle("Log");

        final WebView webView = new WebView(this);

        String logContent = TextUtils.htmlEncode(mLog.toString()).replace("\n", "<br />");
        String logHtml = "<html><body><pre>" + logContent + "</pre></body></html>";
        webView.loadData(logHtml, "text/html", "utf-8");

        logDialogBuilder.setPositiveButton("Copy", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                clipboardManager.setText(mLog.toString());
            }
        });

        logDialogBuilder.setView(webView);

        logDialogBuilder.create().show();
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.nttec.everychan.chans.fourchan.FourchanModule.java

private void addPasscodePreference(PreferenceGroup preferenceGroup) {
    final Context context = preferenceGroup.getContext();
    PreferenceScreen passScreen = preferenceGroup.getPreferenceManager().createPreferenceScreen(context);
    passScreen.setTitle("4chan pass");
    EditTextPreference passTokenPreference = new EditTextPreference(context);
    EditTextPreference passPINPreference = new EditTextPreference(context);
    Preference passLoginPreference = new Preference(context);
    Preference passClearPreference = new Preference(context);
    passTokenPreference.setTitle("Token");
    passTokenPreference.setDialogTitle("Token");
    passTokenPreference.setKey(getSharedKey(PREF_KEY_PASS_TOKEN));
    passTokenPreference.getEditText().setSingleLine();
    passTokenPreference.getEditText()//from   w w  w . j a  v a2 s  .  co m
            .setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
    passPINPreference.setTitle("PIN");
    passPINPreference.setDialogTitle("PIN");
    passPINPreference.setKey(getSharedKey(PREF_KEY_PASS_PIN));
    passPINPreference.getEditText().setSingleLine();
    passPINPreference.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
    passLoginPreference.setTitle("Log In");
    passLoginPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            if (!useHttps())
                Toast.makeText(context, "Using HTTPS even if HTTP is selected", Toast.LENGTH_SHORT).show();
            final String token = preferences.getString(getSharedKey(PREF_KEY_PASS_TOKEN), "");
            final String pin = preferences.getString(getSharedKey(PREF_KEY_PASS_PIN), "");
            final String authUrl = "https://sys.4chan.org/auth"; //only https
            final CancellableTask passAuthTask = new CancellableTask.BaseCancellableTask();
            final ProgressDialog passAuthProgressDialog = new ProgressDialog(context);
            passAuthProgressDialog.setMessage("Logging in");
            passAuthProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    passAuthTask.cancel();
                }
            });
            passAuthProgressDialog.setCanceledOnTouchOutside(false);
            passAuthProgressDialog.show();
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (passAuthTask.isCancelled())
                            return;
                        setPasscodeCookie(null, true);
                        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                        pairs.add(new BasicNameValuePair("act", "do_login"));
                        pairs.add(new BasicNameValuePair("id", token));
                        pairs.add(new BasicNameValuePair("pin", pin));
                        HttpRequestModel request = HttpRequestModel.builder()
                                .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8")).build();
                        String response = HttpStreamer.getInstance().getStringFromUrl(authUrl, request,
                                httpClient, null, passAuthTask, false);
                        if (passAuthTask.isCancelled())
                            return;
                        if (response.contains("Your device is now authorized")) {
                            String passId = null;
                            for (Cookie cookie : httpClient.getCookieStore().getCookies()) {
                                if (cookie.getName().equals("pass_id")) {
                                    String value = cookie.getValue();
                                    if (!value.equals("0")) {
                                        passId = value;
                                        break;
                                    }
                                }
                            }
                            if (passId == null) {
                                showToast("Could not get pass id");
                            } else {
                                setPasscodeCookie(passId, true);
                                showToast("Success! Your device is now authorized.");
                            }
                        } else if (response.contains("Your Token must be exactly 10 characters")) {
                            showToast("Incorrect token");
                        } else if (response.contains("You have left one or more fields blank")) {
                            showToast("You have left one or more fields blank");
                        } else if (response.contains("Incorrect Token or PIN")) {
                            showToast("Incorrect Token or PIN");
                        } else {
                            Matcher m = Pattern
                                    .compile("<strong style=\"color: red; font-size: larger;\">(.*?)</strong>")
                                    .matcher(response);
                            if (m.find()) {
                                showToast(m.group(1));
                            } else {
                                showWebView(response);
                            }
                        }
                    } catch (Exception e) {
                        showToast(e.getMessage() == null ? resources.getString(R.string.error_unknown)
                                : e.getMessage());
                    } finally {
                        passAuthProgressDialog.dismiss();
                    }
                }

                private void showToast(final String message) {
                    if (context instanceof Activity) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }

                private void showWebView(final String html) {
                    if (context instanceof Activity) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                WebView webView = new WebView(context);
                                webView.getSettings().setSupportZoom(true);
                                webView.loadData(html, "text/html", null);
                                new AlertDialog.Builder(context).setView(webView)
                                        .setNeutralButton(android.R.string.ok, null).show();
                            }
                        });
                    }
                }
            });
            return true;
        }
    });
    passClearPreference.setTitle("Reset pass cookie");
    passClearPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            setPasscodeCookie(null, true);
            Toast.makeText(context, "Cookie is reset", Toast.LENGTH_LONG).show();
            return true;
        }
    });
    passScreen.addPreference(passTokenPreference);
    passScreen.addPreference(passPINPreference);
    passScreen.addPreference(passLoginPreference);
    passScreen.addPreference(passClearPreference);
    preferenceGroup.addPreference(passScreen);
}