Example usage for android.content ClipboardManager setPrimaryClip

List of usage examples for android.content ClipboardManager setPrimaryClip

Introduction

In this page you can find the example usage for android.content ClipboardManager setPrimaryClip.

Prototype

public void setPrimaryClip(@NonNull ClipData clip) 

Source Link

Document

Sets the current primary clip on the clipboard.

Usage

From source file:org.sufficientlysecure.keychain.ui.ViewKeyAdvShareFragment.java

private void shareKey(boolean toClipboard) {
    Activity activity = getActivity();/*  w w w.j av a 2 s.c  o m*/
    if (activity == null || mFingerprint == null) {
        return;
    }
    ProviderHelper providerHelper = new ProviderHelper(activity);

    try {
        String content = providerHelper
                .getKeyRingAsArmoredString(KeychainContract.KeyRingData.buildPublicKeyRingUri(mDataUri));

        if (toClipboard) {
            ClipboardManager clipMan = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
            if (clipMan == null) {
                Notify.create(activity, R.string.error_clipboard_copy, Style.ERROR);
                return;
            }

            ClipData clip = ClipData.newPlainText(Constants.CLIPBOARD_LABEL, content);
            clipMan.setPrimaryClip(clip);

            Notify.create(activity, R.string.key_copied_to_clipboard, Notify.Style.OK).show();
            return;
        }

        // let user choose application
        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.setType(Constants.MIME_TYPE_KEYS);

        // NOTE: Don't use Intent.EXTRA_TEXT to send the key
        // better send it via a Uri!
        // example: Bluetooth Share will convert text/plain sent via Intent.EXTRA_TEXT to HTML
        try {
            TemporaryFileProvider shareFileProv = new TemporaryFileProvider();

            String filename = KeyFormattingUtils.convertFingerprintToHex(mFingerprint);
            OpenPgpUtils.UserId mainUserId = KeyRing.splitUserId(mUserId);
            if (mainUserId.name != null) {
                filename = mainUserId.name;
            }
            Uri contentUri = TemporaryFileProvider.createFile(activity,
                    filename + Constants.FILE_EXTENSION_ASC);

            BufferedWriter contentWriter = new BufferedWriter(new OutputStreamWriter(
                    new ParcelFileDescriptor.AutoCloseOutputStream(shareFileProv.openFile(contentUri, "w"))));
            contentWriter.write(content);
            contentWriter.close();

            sendIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
        } catch (FileNotFoundException e) {
            Log.e(Constants.TAG, "Error creating temporary key share file!", e);
            // no need for a snackbar because one sharing option doesn't work
            // Notify.create(getActivity(), R.string.error_temp_file, Notify.Style.ERROR).show();
        }

        String title = getString(R.string.title_share_key);
        Intent shareChooser = Intent.createChooser(sendIntent, title);

        startActivity(shareChooser);
    } catch (PgpGeneralException | IOException e) {
        Log.e(Constants.TAG, "error processing key!", e);
        Notify.create(activity, R.string.error_key_processing, Notify.Style.ERROR).show();
    } catch (ProviderHelper.NotFoundException e) {
        Log.e(Constants.TAG, "key not found!", e);
        Notify.create(activity, R.string.error_key_not_found, Notify.Style.ERROR).show();
    }
}

From source file:com.app.uafeed.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;//from  w  ww . j  ava2 s . c  o m

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.rating_important);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.rating_not_important);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            if (link != null) {
                String title = cursor.getString(mTitlePos);
                startActivity(Intent.createChooser(
                        new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                        getString(R.string.menu_share)));
            }
            break;
        }
        case R.id.menu_full_screen: {
            toggleFullScreen();
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        }
    }

    return true;
}

From source file:de.blinkt.openvpn.fragments.LogFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ListView lv = getListView();/* www .  j  av a2s .c o  m*/

    lv.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            ClipboardManager clipboard = (ClipboardManager) getActivity()
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Log Entry", ((TextView) view).getText());
            clipboard.setPrimaryClip(clip);
            Toast.makeText(getActivity(), R.string.copied_entry, Toast.LENGTH_SHORT).show();
            return true;
        }
    });
}

From source file:com.viktorrudometkin.burramys.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;//from  ww  w . jav  a 2 s . com

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.rating_important);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.rating_not_important);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    String title = cursor.getString(mTitlePos);
                    startActivity(Intent.createChooser(
                            new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                    .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                            getString(R.string.menu_share)));
                }
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            UiUtils.showMessage(getActivity(), R.string.copied_clipboard);
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        }
    }

    return true;
}

From source file:jahirfiquitiva.iconshowcase.fragments.DonationsFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    /* Flattr *///  w  ww  .  j  a  v a  2 s . co m
    if (mFlattrEnabled) {
        // inflate flattr view into stub
        ViewStub flattrViewStub = (ViewStub) getActivity().findViewById(R.id.donations__flattr_stub);
        flattrViewStub.inflate();

        buildFlattrView();
    }

    /* Google */
    if (mGoogleEnabled) {
        // inflate google view into stub
        ViewStub googleViewStub = (ViewStub) getActivity().findViewById(R.id.donations__google_stub);
        googleViewStub.inflate();

        // choose donation amount
        mGoogleSpinner = (Spinner) getActivity().findViewById(R.id.donations__google_android_market_spinner);
        ArrayAdapter<CharSequence> adapter;
        if (mDebug) {
            adapter = new ArrayAdapter<CharSequence>(getActivity(), android.R.layout.simple_spinner_item,
                    CATALOG_DEBUG);
        } else {
            adapter = new ArrayAdapter<CharSequence>(getActivity(), android.R.layout.simple_spinner_item,
                    mGoogleCatalogValues);
        }
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mGoogleSpinner.setAdapter(adapter);

        Button btGoogle = (Button) getActivity()
                .findViewById(R.id.donations__google_android_market_donate_button);
        btGoogle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                donateGoogleOnClick(v);
            }
        });

        // Create the helper, passing it our context and the public key to verify signatures with
        if (mDebug)
            Utils.showLog(context, "Creating IAB helper.");
        mHelper = new IabHelper(getActivity(), mGooglePubkey);

        // enable debug logging (for a production application, you should set this to false).
        mHelper.enableDebugLogging(mDebug);

        // Start setup. This is asynchronous and the specified listener
        // will be called once setup completes.
        if (mDebug)
            Utils.showLog(context, "Starting setup.");
        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
            public void onIabSetupFinished(IabResult result) {
                if (mDebug)
                    Utils.showLog(context, "Setup finished.");

                if (!result.isSuccess()) {
                    // Oh noes, there was a problem.
                    openDialog(android.R.drawable.ic_dialog_alert,
                            R.string.donations__google_android_market_not_supported_title,
                            getString(R.string.donations__google_android_market_not_supported));
                }

            }
        });
    }

    /* PayPal */
    if (mPaypalEnabled) {
        // inflate paypal view into stub
        ViewStub paypalViewStub = (ViewStub) getActivity().findViewById(R.id.donations__paypal_stub);
        paypalViewStub.inflate();

        Button btPayPal = (Button) getActivity().findViewById(R.id.donations__paypal_donate_button);
        btPayPal.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                donatePayPalOnClick(v);
            }
        });
    }

    /* Bitcoin */
    if (mBitcoinEnabled) {
        // inflate bitcoin view into stub
        ViewStub bitcoinViewStub = (ViewStub) getActivity().findViewById(R.id.donations__bitcoin_stub);
        bitcoinViewStub.inflate();

        Button btBitcoin = (Button) getActivity().findViewById(R.id.donations__bitcoin_button);
        btBitcoin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                donateBitcoinOnClick(v);
            }
        });
        btBitcoin.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                // http://stackoverflow.com/a/11012443/832776
                if (Build.VERSION.SDK_INT >= 11) {
                    ClipboardManager clipboard = (ClipboardManager) getActivity()
                            .getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clip = ClipData.newPlainText(mBitcoinAddress, mBitcoinAddress);
                    clipboard.setPrimaryClip(clip);
                } else {
                    @SuppressWarnings("deprecation")
                    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getActivity()
                            .getSystemService(Context.CLIPBOARD_SERVICE);
                    clipboard.setText(mBitcoinAddress);
                }
                Toast.makeText(getActivity(), R.string.donations__bitcoin_toast_copy, Toast.LENGTH_SHORT)
                        .show();
                return true;
            }
        });
    }
}

From source file:com.normalexception.app.rx8club.view.threadpost.PostView.java

/**
 * Setup our view here.  After the view has been inflated and all of the
 * view objects have been initialized, we can inflate our view here
 * @param post      The model we are going to use to populate the view
 * @param position   Get the position of this view on the window
 * @param listener  The listener object to attach to the view
 *//*from ww w. ja  va2 s. co m*/
public void setPost(final PostModel post, final int position, final OnClickListener listener) {
    username.setText(post.getUserName());
    userTitle.setText(post.getUserTitle());
    userPosts.setText(post.getUserPostCount());
    userJoin.setText(post.getJoinDate());
    postDate.setText(post.getPostDate());
    reportbutton.setVisibility(View.VISIBLE);

    if (PreferenceHelper.isShowLikes(getContext())) {
        if (post.getLikes().size() > 0) {
            String delim = "", likes = "Liked by: ";
            for (String like : post.getLikes()) {
                likes += delim + like;
                delim = ", ";
            }
            likeText.setText(likes);
        } else {
            likeText.setVisibility(View.GONE);
        }
    } else {
        likeText.setVisibility(View.GONE);
    }

    // Lets make sure we remove any font formatting that was done within
    // the text
    String trimmedPost = post.getUserPost().replaceAll("(?i)<(/*)font(.*?)>", "");

    // Show attachments if the preference allows it
    if (PreferenceHelper.isShowAttachments(getContext()))
        trimmedPost = appendAttachments(trimmedPost, post.getAttachments());

    // Show signatures if the preference allows it
    if (PreferenceHelper.isShowSignatures(getContext()) && post.getUserSignature() != null)
        trimmedPost = appendSignature(trimmedPost, post.getUserSignature());

    // Set html Font color
    trimmedPost = Utils.postFormatter(trimmedPost, getContext());
    postText.setBackgroundColor(Color.DKGRAY);
    postText.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    postText.getSettings().setAppCachePath(Cache.getExternalCacheDir(getContext()).getAbsolutePath());
    postText.getSettings().setAllowFileAccess(false);
    postText.getSettings().setAppCacheEnabled(true);
    postText.getSettings().setJavaScriptEnabled(false);
    postText.getSettings().setSupportZoom(false);
    postText.getSettings().setSupportMultipleWindows(false);
    postText.getSettings().setUserAgentString(WebUrls.USER_AGENT);
    postText.getSettings().setDatabaseEnabled(false);
    postText.getSettings().setDomStorageEnabled(false);
    postText.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
    postText.setOnTouchListener(new View.OnTouchListener() {
        @SuppressLint("ClickableViewAccessibility")
        public boolean onTouch(View v, MotionEvent event) {
            return (event.getAction() == MotionEvent.ACTION_MOVE);
        }
    });
    postText.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // Check if the URL for the site, and if it is a thread or a category
            Log.d(TAG, "User Clicked Embedded url");
            boolean isThread = false;
            if (url.contains("rx8club.com")) {
                isThread = url.matches(".*\\-\\d+\\/$");
                Log.d(TAG, String.format("The Link (%s) is %sa thread", url, (isThread) ? "" : "NOT "));

                Bundle args = new Bundle();
                args.putString("link", url);

                if (isThread) {
                    FragmentUtils.fragmentTransaction((FragmentActivity) view.getContext(),
                            ThreadFragment.newInstance(), false, true, args);
                    return true;
                }
            }

            // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            MainApplication.getAppContext().startActivity(intent);
            return true;
        }
    });

    postText.loadDataWithBaseURL(WebUrls.rootUrl, trimmedPost, "text/html", "utf-8", "");

    // Load up the avatar of hte user, but remember to remove
    // the dateline at the end of the file so that we aren't
    // creating multiple images for a user.  The image still
    // gets returned without a date
    if (PreferenceHelper.isShowAvatars(getContext())) {
        String nodate_avatar = post.getUserImageUrl().indexOf('?') == -1 ? post.getUserImageUrl()
                : post.getUserImageUrl().substring(0, post.getUserImageUrl().indexOf('?'));

        if (!nodate_avatar.isEmpty()) {
            imageLoader.DisplayImage(nodate_avatar, avatar);
        } else {
            avatar.setImageResource(R.drawable.rotor_icon);
        }
    }

    // Display the right items if the user is logged in
    setUserIcons(this, post.isLoggedInUser());

    downButton.setOnClickListener(listener);

    // Set click listeners if we are logged in, hide the buttons
    // if we are not logged in
    if (LoginFactory.getInstance().isGuestMode()) {
        quoteButton.setVisibility(View.GONE);
        editButton.setVisibility(View.GONE);
        pmButton.setVisibility(View.GONE);
        deleteButton.setVisibility(View.GONE);
        reportbutton.setVisibility(View.GONE);
    } else {
        quoteButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Log.d(TAG, "Quote Clicked");
                String txt = Html.fromHtml(post.getUserPost()).toString();
                String finalText = String.format("[quote=%s]%s[/quote]", post.getUserName(), txt);
                postBox.setText(finalText);
                postBox.requestFocus();
            }
        });

        editButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Log.d(TAG, "Edit Clicked");

                // Create new fragment and transaction
                Bundle args = new Bundle();
                args.putString("postid", post.getPostId());
                args.putString("securitytoken", post.getToken());
                Fragment newFragment = new EditPostFragment();

                FragmentUtils.fragmentTransaction((FragmentActivity) getContext(), newFragment, true, true,
                        args);
            }
        });

        reportbutton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Log.d(TAG, "Report Clicked");
                new ReportPostDialog(getContext(), post.getToken(), post.getPostId()).show();
            }
        });

        linkbutton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Log.d(TAG, "Link Clicked");
                ClipboardManager clipboard = (android.content.ClipboardManager) getContext()
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                android.content.ClipData clip = android.content.ClipData.newPlainText("thread link",
                        post.getRootThreadUrl());
                clipboard.setPrimaryClip(clip);
                Toast.makeText(getContext(), "Thread Link Copied To Clipboard", Toast.LENGTH_LONG).show();
            }
        });

        pmButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Log.d(TAG, "PM Clicked");

                // Create new fragment and transaction
                Bundle args = new Bundle();
                args.putString("user", post.getUserName());
                Fragment newFragment = new NewPrivateMessageFragment();
                FragmentUtils.fragmentTransaction((FragmentActivity) getContext(), newFragment, false, true,
                        args);
            }
        });

        final boolean isFirstPost = (position == 0);
        deleteButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                        case DialogInterface.BUTTON_POSITIVE:
                            // Create new fragment and transaction
                            Bundle args = new Bundle();
                            args.putString("postid", post.getPostId());
                            args.putString("securitytoken", post.getToken());
                            args.putBoolean("delete", true);
                            args.putBoolean("deleteThread", isFirstPost && post.isLoggedInUser());
                            Fragment newFragment = new EditPostFragment();
                            FragmentUtils.fragmentTransaction((FragmentActivity) getContext(), newFragment,
                                    false, true, args);
                            break;
                        }
                    }
                };

                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setMessage("Are you sure you want to delete your post?")
                        .setPositiveButton("Yes", dialogClickListener)
                        .setNegativeButton("No", dialogClickListener).show();
            }
        });
    }
}

From source file:de.baumann.browser.popups.Popup_readLater.java

private void setReadLaterList() {

    //display data
    final int layoutstyle = R.layout.list_item;
    int[] xml_id = new int[] { R.id.textView_title_notes, R.id.textView_des_notes, R.id.textView_create_notes };
    String[] column = new String[] { "readLater_title", "readLater_content", "readLater_creation" };
    final Cursor row = db.fetchAllData(this);
    adapter = new SimpleCursorAdapter(this, layoutstyle, row, column, xml_id, 0);

    //display data by filter
    final String note_search = sharedPref.getString("filter_readLaterBY", "readLater_title");
    sharedPref.edit().putString("filter_readLaterBY", "readLater_title").apply();
    editText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }/* w w  w  . j av  a 2s.  c  o  m*/

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s.toString());
        }
    });
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return db.fetchDataByFilter(constraint.toString(), note_search);
        }
    });

    listView.setAdapter(adapter);
    //onClick function
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {

            Cursor row = (Cursor) listView.getItemAtPosition(position);
            final String readLater_content = row.getString(row.getColumnIndexOrThrow("readLater_content"));
            sharedPref.edit().putString("openURL", readLater_content).apply();
            finish();
        }
    });

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            Cursor row2 = (Cursor) listView.getItemAtPosition(position);
            final String _id = row2.getString(row2.getColumnIndexOrThrow("_id"));
            final String readLater_title = row2.getString(row2.getColumnIndexOrThrow("readLater_title"));
            final String readLater_content = row2.getString(row2.getColumnIndexOrThrow("readLater_content"));
            final String readLater_icon = row2.getString(row2.getColumnIndexOrThrow("readLater_icon"));
            final String readLater_attachment = row2
                    .getString(row2.getColumnIndexOrThrow("readLater_attachment"));
            final String readLater_creation = row2.getString(row2.getColumnIndexOrThrow("readLater_creation"));

            final CharSequence[] options = { getString(R.string.menu_share), getString(R.string.menu_save),
                    getString(R.string.bookmark_edit_title), getString(R.string.bookmark_remove_bookmark) };
            new AlertDialog.Builder(Popup_readLater.this)
                    .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    }).setItems(options, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            if (options[item].equals(getString(R.string.bookmark_edit_title))) {
                                sharedPref.edit().putString("edit_id", _id).apply();
                                sharedPref.edit().putString("edit_content", readLater_content).apply();
                                sharedPref.edit().putString("edit_icon", readLater_icon).apply();
                                sharedPref.edit().putString("edit_attachment", readLater_attachment).apply();
                                sharedPref.edit().putString("edit_creation", readLater_creation).apply();
                                editText.setVisibility(View.VISIBLE);
                                helper_editText.showKeyboard(Popup_readLater.this, editText, 2, readLater_title,
                                        getString(R.string.bookmark_edit_title));
                            }

                            if (options[item].equals(getString(R.string.bookmark_remove_bookmark))) {
                                Snackbar snackbar = Snackbar
                                        .make(listView, R.string.bookmark_remove_confirmation,
                                                Snackbar.LENGTH_LONG)
                                        .setAction(R.string.toast_yes, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                db.delete(Integer.parseInt(_id));
                                                setReadLaterList();
                                            }
                                        });
                                snackbar.show();
                            }

                            if (options[item].equals(getString(R.string.menu_share))) {
                                final CharSequence[] options = { getString(R.string.menu_share_link),
                                        getString(R.string.menu_share_link_copy) };
                                new AlertDialog.Builder(Popup_readLater.this)
                                        .setPositiveButton(R.string.toast_cancel,
                                                new DialogInterface.OnClickListener() {

                                                    public void onClick(DialogInterface dialog,
                                                            int whichButton) {
                                                        dialog.cancel();
                                                    }
                                                })
                                        .setItems(options, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int item) {
                                                if (options[item].equals(getString(R.string.menu_share_link))) {
                                                    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                                                    sharingIntent.setType("text/plain");
                                                    sharingIntent.putExtra(Intent.EXTRA_SUBJECT,
                                                            readLater_title);
                                                    sharingIntent.putExtra(Intent.EXTRA_TEXT,
                                                            readLater_content);
                                                    startActivity(Intent.createChooser(sharingIntent,
                                                            (getString(R.string.app_share_link))));
                                                }
                                                if (options[item]
                                                        .equals(getString(R.string.menu_share_link_copy))) {
                                                    ClipboardManager clipboard = (ClipboardManager) Popup_readLater.this
                                                            .getSystemService(Context.CLIPBOARD_SERVICE);
                                                    clipboard.setPrimaryClip(
                                                            ClipData.newPlainText("text", readLater_content));
                                                    Snackbar.make(listView, R.string.context_linkCopy_toast,
                                                            Snackbar.LENGTH_SHORT).show();
                                                }
                                            }
                                        }).show();
                            }
                            if (options[item].equals(getString(R.string.menu_save))) {
                                final CharSequence[] options = { getString(R.string.menu_save_bookmark),
                                        getString(R.string.menu_save_pass),
                                        getString(R.string.menu_createShortcut) };
                                new AlertDialog.Builder(Popup_readLater.this)
                                        .setPositiveButton(R.string.toast_cancel,
                                                new DialogInterface.OnClickListener() {

                                                    public void onClick(DialogInterface dialog,
                                                            int whichButton) {
                                                        dialog.cancel();
                                                    }
                                                })
                                        .setItems(options, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int item) {
                                                if (options[item].equals(getString(R.string.menu_save_pass))) {
                                                    helper_editText.editText_savePass(Popup_readLater.this,
                                                            listView, readLater_title, readLater_content);
                                                }
                                                if (options[item]
                                                        .equals(getString(R.string.menu_save_bookmark))) {
                                                    DbAdapter_Bookmarks db = new DbAdapter_Bookmarks(
                                                            Popup_readLater.this);
                                                    db.open();

                                                    if (db.isExist(readLater_content)) {
                                                        Snackbar.make(listView,
                                                                getString(R.string.toast_newTitle),
                                                                Snackbar.LENGTH_LONG).show();
                                                    } else {
                                                        db.insert(readLater_title, readLater_content, "", "",
                                                                helper_main.createDate());
                                                        Snackbar.make(listView, R.string.bookmark_added,
                                                                Snackbar.LENGTH_LONG).show();
                                                    }
                                                }
                                                if (options[item]
                                                        .equals(getString(R.string.menu_createShortcut))) {
                                                    Intent i = new Intent();
                                                    i.setAction(Intent.ACTION_VIEW);
                                                    i.setClassName(Popup_readLater.this,
                                                            "de.baumann.browser.Browser_left");
                                                    i.setData(Uri.parse(readLater_content));

                                                    Intent shortcut = new Intent();
                                                    shortcut.putExtra("android.intent.extra.shortcut.INTENT",
                                                            i);
                                                    shortcut.putExtra("android.intent.extra.shortcut.NAME",
                                                            "THE NAME OF SHORTCUT TO BE SHOWN");
                                                    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
                                                            readLater_content);
                                                    shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                                                            Intent.ShortcutIconResource.fromContext(
                                                                    Popup_readLater.this
                                                                            .getApplicationContext(),
                                                                    R.mipmap.ic_launcher));
                                                    shortcut.setAction(
                                                            "com.android.launcher.action.INSTALL_SHORTCUT");
                                                    Popup_readLater.this.sendBroadcast(shortcut);
                                                    Snackbar.make(listView,
                                                            R.string.menu_createShortcut_success,
                                                            Snackbar.LENGTH_SHORT).show();
                                                }
                                            }
                                        }).show();
                            }

                        }
                    }).show();
            return true;
        }
    });

    listView.post(new Runnable() {
        public void run() {
            listView.setSelection(listView.getCount() - 1);
        }
    });
}

From source file:net.sourceforge.fidocadj.FidoMain.java

/** Stores the given String in the clipboard.
*//*from w  w w  .  ja  v a 2s  .  c  o m*/
public void copyText(String s) {
    // Gets a handle to the clipboard service.
    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    ClipData clip = ClipData.newPlainText("simple text", s.toString());
    clipboard.setPrimaryClip(clip);
}

From source file:com.flym.dennikn.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;//  ww  w.j  a  v  a 2 s  .c om

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.rating_important);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.rating_not_important);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    String title = cursor.getString(mTitlePos);
                    startActivity(Intent.createChooser(
                            new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                    .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                            getString(R.string.menu_share)));
                }
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        }
    }

    return true;
}

From source file:de.baumann.browser.popups.Popup_history.java

private void setHistoryList() {

    //display data
    final int layoutstyle = R.layout.list_item;
    int[] xml_id = new int[] { R.id.textView_title_notes, R.id.textView_des_notes, R.id.textView_create_notes };
    String[] column = new String[] { "history_title", "history_content", "history_creation" };
    final Cursor row = db.fetchAllData(this);
    adapter = new SimpleCursorAdapter(this, layoutstyle, row, column, xml_id, 0);

    //display data by filter
    final String note_search = sharedPref.getString("filter_historyBY", "history_title");
    sharedPref.edit().putString("filter_historyBY", "history_title").apply();
    editText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }/*from   ww  w  .  j  av  a2s  . c  o  m*/

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s.toString());
        }
    });
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return db.fetchDataByFilter(constraint.toString(), note_search);
        }
    });

    listView.setAdapter(adapter);
    //onClick function
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {

            Cursor row = (Cursor) listView.getItemAtPosition(position);
            final String history_content = row.getString(row.getColumnIndexOrThrow("history_content"));
            sharedPref.edit().putString("openURL", history_content).apply();
            finish();
        }
    });

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            Cursor row2 = (Cursor) listView.getItemAtPosition(position);
            final String _id = row2.getString(row2.getColumnIndexOrThrow("_id"));
            final String history_title = row2.getString(row2.getColumnIndexOrThrow("history_title"));
            final String history_content = row2.getString(row2.getColumnIndexOrThrow("history_content"));
            final String history_icon = row2.getString(row2.getColumnIndexOrThrow("history_icon"));
            final String history_attachment = row2.getString(row2.getColumnIndexOrThrow("history_attachment"));
            final String history_creation = row2.getString(row2.getColumnIndexOrThrow("history_creation"));

            final CharSequence[] options = { getString(R.string.menu_share), getString(R.string.menu_save),
                    getString(R.string.bookmark_edit_title), getString(R.string.bookmark_remove_bookmark) };
            new AlertDialog.Builder(Popup_history.this)
                    .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    }).setItems(options, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            if (options[item].equals(getString(R.string.bookmark_edit_title))) {
                                sharedPref.edit().putString("edit_id", _id).apply();
                                sharedPref.edit().putString("edit_content", history_content).apply();
                                sharedPref.edit().putString("edit_icon", history_icon).apply();
                                sharedPref.edit().putString("edit_attachment", history_attachment).apply();
                                sharedPref.edit().putString("edit_creation", history_creation).apply();
                                editText.setVisibility(View.VISIBLE);
                                helper_editText.showKeyboard(Popup_history.this, editText, 2, history_title,
                                        getString(R.string.bookmark_edit_title));
                            }

                            if (options[item].equals(getString(R.string.bookmark_remove_bookmark))) {
                                Snackbar snackbar = Snackbar
                                        .make(listView, R.string.bookmark_remove_confirmation,
                                                Snackbar.LENGTH_LONG)
                                        .setAction(R.string.toast_yes, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                db.delete(Integer.parseInt(_id));
                                                setHistoryList();
                                            }
                                        });
                                snackbar.show();
                            }

                            if (options[item].equals(getString(R.string.menu_share))) {
                                final CharSequence[] options = { getString(R.string.menu_share_link),
                                        getString(R.string.menu_share_link_copy) };
                                new AlertDialog.Builder(Popup_history.this)
                                        .setPositiveButton(R.string.toast_cancel,
                                                new DialogInterface.OnClickListener() {

                                                    public void onClick(DialogInterface dialog,
                                                            int whichButton) {
                                                        dialog.cancel();
                                                    }
                                                })
                                        .setItems(options, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int item) {
                                                if (options[item].equals(getString(R.string.menu_share_link))) {
                                                    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                                                    sharingIntent.setType("text/plain");
                                                    sharingIntent.putExtra(Intent.EXTRA_SUBJECT, history_title);
                                                    sharingIntent.putExtra(Intent.EXTRA_TEXT, history_content);
                                                    startActivity(Intent.createChooser(sharingIntent,
                                                            (getString(R.string.app_share_link))));
                                                }
                                                if (options[item]
                                                        .equals(getString(R.string.menu_share_link_copy))) {
                                                    ClipboardManager clipboard = (ClipboardManager) Popup_history.this
                                                            .getSystemService(Context.CLIPBOARD_SERVICE);
                                                    clipboard.setPrimaryClip(
                                                            ClipData.newPlainText("text", history_content));
                                                    Snackbar.make(listView, R.string.context_linkCopy_toast,
                                                            Snackbar.LENGTH_SHORT).show();
                                                }
                                            }
                                        }).show();
                            }
                            if (options[item].equals(getString(R.string.menu_save))) {
                                final CharSequence[] options = { getString(R.string.menu_save_bookmark),
                                        getString(R.string.menu_save_readLater),
                                        getString(R.string.menu_save_pass),
                                        getString(R.string.menu_createShortcut) };
                                new AlertDialog.Builder(Popup_history.this)
                                        .setPositiveButton(R.string.toast_cancel,
                                                new DialogInterface.OnClickListener() {

                                                    public void onClick(DialogInterface dialog,
                                                            int whichButton) {
                                                        dialog.cancel();
                                                    }
                                                })
                                        .setItems(options, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int item) {
                                                if (options[item].equals(getString(R.string.menu_save_pass))) {
                                                    helper_editText.editText_savePass(Popup_history.this,
                                                            listView, history_title, history_content);
                                                }
                                                if (options[item]
                                                        .equals(getString(R.string.menu_save_bookmark))) {

                                                    DbAdapter_Bookmarks db = new DbAdapter_Bookmarks(
                                                            Popup_history.this);
                                                    db.open();

                                                    if (db.isExist(history_content)) {
                                                        Snackbar.make(listView,
                                                                getString(R.string.toast_newTitle),
                                                                Snackbar.LENGTH_LONG).show();
                                                    } else {
                                                        db.insert(history_title, history_content, "", "",
                                                                helper_main.createDate());
                                                        Snackbar.make(listView, R.string.bookmark_added,
                                                                Snackbar.LENGTH_LONG).show();
                                                    }
                                                }
                                                if (options[item]
                                                        .equals(getString(R.string.menu_save_readLater))) {
                                                    DbAdapter_ReadLater db = new DbAdapter_ReadLater(
                                                            Popup_history.this);
                                                    db.open();
                                                    if (db.isExist(history_content)) {
                                                        Snackbar.make(listView,
                                                                getString(R.string.toast_newTitle),
                                                                Snackbar.LENGTH_LONG).show();
                                                    } else {
                                                        db.insert(history_title, history_content, "", "",
                                                                helper_main.createDate());
                                                        Snackbar.make(listView, R.string.bookmark_added,
                                                                Snackbar.LENGTH_LONG).show();
                                                    }
                                                }
                                                if (options[item]
                                                        .equals(getString(R.string.menu_createShortcut))) {
                                                    Intent i = new Intent();
                                                    i.setAction(Intent.ACTION_VIEW);
                                                    i.setClassName(Popup_history.this,
                                                            "de.baumann.browser.Browser_left");
                                                    i.setData(Uri.parse(history_content));

                                                    Intent shortcut = new Intent();
                                                    shortcut.putExtra("android.intent.extra.shortcut.INTENT",
                                                            i);
                                                    shortcut.putExtra("android.intent.extra.shortcut.NAME",
                                                            "THE NAME OF SHORTCUT TO BE SHOWN");
                                                    shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
                                                            history_title);
                                                    shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                                                            Intent.ShortcutIconResource.fromContext(
                                                                    Popup_history.this.getApplicationContext(),
                                                                    R.mipmap.ic_launcher));
                                                    shortcut.setAction(
                                                            "com.android.launcher.action.INSTALL_SHORTCUT");
                                                    Popup_history.this.sendBroadcast(shortcut);
                                                    Snackbar.make(listView,
                                                            R.string.menu_createShortcut_success,
                                                            Snackbar.LENGTH_SHORT).show();
                                                }
                                            }
                                        }).show();
                            }

                        }
                    }).show();
            return true;
        }
    });

    listView.post(new Runnable() {
        public void run() {
            listView.setSelection(listView.getCount() - 1);
        }
    });
}