Example usage for android.text ClipboardManager setText

List of usage examples for android.text ClipboardManager setText

Introduction

In this page you can find the example usage for android.text ClipboardManager setText.

Prototype

public abstract void setText(CharSequence text);

Source Link

Document

Sets the contents of the clipboard to the specified text.

Usage

From source file:tv.acfun.video.CommentsActivity.java

@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override/*from  www.  ja va2 s.c om*/
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    Object o = parent.getItemAtPosition(position);
    if (o == null || !(o instanceof Comment))
        return false;
    Comment c = (Comment) o;
    ClipboardManager ma = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        ClipData text = ClipData.newHtmlText(c.userName, c.content, c.content);
        ((android.content.ClipboardManager) ma).setPrimaryClip(text);
    } else {
        ma.setText(c.content);
    }
    Toast.makeText(this, "#" + c.count + "?", 0).show();
    return true;
}

From source file:org.bombusim.lime.fragments.ChatFragment.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    switch (item.getItemId()) {
    case R.id.cmdCopy:
        try {//from   ww w .  jav a  2s  . c  o m
            String s = ((MessageView) (info.targetView)).toString();

            // Gets a handle to the clipboard service.
            ClipboardManager clipboard = (ClipboardManager) getActivity()
                    .getSystemService(Context.CLIPBOARD_SERVICE);

            // Set the clipboard's primary clip.
            clipboard.setText(s);

        } catch (Exception e) {
        }
        return true;

    case R.id.cmdDelete:

        chatListView.setVisibility(View.GONE);
        mChat.removeFromHistory(info.id);
        refreshVisualContent();

        return true;

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

From source file:org.profeda.dictionary.SearchActivity.java

/**
 * Called when the activity is first created.
 *//* w ww.j av  a 2 s. c o m*/
@Override
public void onCreate(Bundle savedInstanceState) {
    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(SearchActivity.this);

    if (pref.getBoolean("show_changelog", true) == true) {
        MessageBox.showChangeLog(this);
    }

    loadDictionaries(pref);

    if (pref.getBoolean("p_invert_colors", false) == true) {
        setTheme(R.style.Light);
    } else {
        setTheme(R.style.Dark);
    }

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    dict = new Dict(this, pref.getString("dictFile", null));

    updateTitleBar();
    readMRU();

    final EditText searchbox = (EditText) findViewById(R.id.searchbox);
    final Button dictselectbutton = (Button) findViewById(R.id.dictselectbutton);
    final ListView listview = (ListView) findViewById(R.id.contentlist);

    listview.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView l, View v, int position, long id) {
            ListAdapter la = ((ListView) l).getAdapter();
            if (la instanceof GenericStringAdapter) {
                final String data = (String) la.getItem(position);
                if (data.startsWith("> ")) {
                    searchbox.setText(data.substring(2));
                    doSearch(true);
                }
            } else if (la instanceof DictListAdapter) {
                final String[] data = (String[]) la.getItem(position);

                final List<Dict> langs = Dict.searchForLanguage(SearchActivity.this, dict.toLang, null);

                String[] menu = new String[langs.size() + 1];
                menu[0] = getString(R.string.copy_translation_to_clipboard);
                for (int i = 1; i < menu.length; i++)
                    menu[i] = String.format(getString(R.string.search_translation_in_language),
                            langs.get(i - 1).toLang);

                Matcher m = Pattern.compile("<b>(.*)<\\/b>.*").matcher(data[1]);
                if (!m.matches())
                    return;
                final String translation = m.group(1).trim();

                new AlertDialog.Builder(SearchActivity.this).setIcon(android.R.drawable.ic_dialog_info)
                        .setTitle(translation).setItems(menu, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                switch (arg1) {
                                case 0:
                                    ClipboardManager cm = (ClipboardManager) getSystemService(
                                            CLIPBOARD_SERVICE);
                                    cm.setText(translation);
                                    break;
                                default:
                                    dict = langs.get(arg1 - 1);
                                    readMRU();
                                    updateTitleBar();
                                    searchbox.setText(translation);
                                    doSearch(true);
                                }
                            }
                        }).show();
            }
        }
    });

    searchbox.setOnEditorActionListener(new EditText.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE
                    || event.getAction() == KeyEvent.ACTION_DOWN
                            && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                doSearch(true);
                return true;
            } else {
                return false;
            }
        }
    });

    final Drawable deleteIcon = getResources().getDrawable(R.drawable.textbox_clear);
    //deleteIcon.setBounds(0, 0, deleteIcon.getIntrinsicWidth(), deleteIcon.getIntrinsicHeight());
    deleteIcon.setBounds(0, 0, 51, 30); // wtf??? die Zahlen sind empirisch ermittelt... ab right>=52 springt die hhe des editText

    searchbox.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            searchbox.setCompoundDrawables(null, null, s.toString().equals("") ? null : deleteIcon, null);
            //searchbox.setCompoundDrawablesWithIntrinsicBounds(null, null, s.toString().equals("") ? null : deleteIcon, null);
            searchbox.setCompoundDrawablePadding(0);
        }

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

        @Override
        public void afterTextChanged(Editable s) {
            if (enableLivesearch && s.length() > 1 && dict.filePrefix != null && dictSearchInAction == false) {
                DictionarySearcher ds = new DictionarySearcher();
                ds.targetList = (ListView) findViewById(R.id.contentlist);
                ds.execute(dict.filePrefix, s.toString());
            }
            if (s.length() == 0) {
                displayMRU();
            }
        }
    });

    //searchbox.setCompoundDrawables(null, null, deleteIcon, null);
    searchbox.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (searchbox.getCompoundDrawables()[2] == null) {
                return false;
            }
            if (event.getAction() != MotionEvent.ACTION_UP) {
                return false;
            }
            if (event.getX() > searchbox.getWidth() - searchbox.getPaddingRight()
                    - deleteIcon.getIntrinsicWidth()) {
                searchbox.setText("");
                searchbox.setCompoundDrawables(null, null, null, null);
            }
            return false;
        }
    });

    dictselectbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectDictionary();
        }
    });

    ((Button) findViewById(R.id.dictswapbutton)).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            final List<Dict> langs = Dict.searchForLanguage(SearchActivity.this, dict.toLang, dict.fromLang);
            if (langs.size() > 0) {
                dict = langs.get(0);
                readMRU();
                updateTitleBar();
                searchbox.setText("");
            } else {
                MessageBox.alert(SearchActivity.this, getString(R.string.no_reverse_dict_found));
            }
        }
    });

}

From source file:org.petero.droidfish.activities.EditBoard.java

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case EDIT_DIALOG: {
        final int SIDE_TO_MOVE = 0;
        final int CLEAR_BOARD = 1;
        final int INITIAL_POS = 2;
        final int CASTLING_FLAGS = 3;
        final int EN_PASSANT_FILE = 4;
        final int MOVE_COUNTERS = 5;
        final int COPY_POSITION = 6;
        final int PASTE_POSITION = 7;
        final int GET_FEN = 8;

        List<CharSequence> lst = new ArrayList<CharSequence>();
        List<Integer> actions = new ArrayList<Integer>();
        lst.add(getString(R.string.side_to_move));
        actions.add(SIDE_TO_MOVE);/*  w  w  w  . j  av  a2 s. c o m*/
        lst.add(getString(R.string.clear_board));
        actions.add(CLEAR_BOARD);
        lst.add(getString(R.string.initial_position));
        actions.add(INITIAL_POS);
        lst.add(getString(R.string.castling_flags));
        actions.add(CASTLING_FLAGS);
        lst.add(getString(R.string.en_passant_file));
        actions.add(EN_PASSANT_FILE);
        lst.add(getString(R.string.move_counters));
        actions.add(MOVE_COUNTERS);
        lst.add(getString(R.string.copy_position));
        actions.add(COPY_POSITION);
        lst.add(getString(R.string.paste_position));
        actions.add(PASTE_POSITION);
        if (DroidFish.hasFenProvider(getPackageManager())) {
            lst.add(getString(R.string.get_fen));
            actions.add(GET_FEN);
        }
        final List<Integer> finalActions = actions;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.edit_board);
        builder.setItems(lst.toArray(new CharSequence[lst.size()]), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                switch (finalActions.get(item)) {
                case SIDE_TO_MOVE:
                    showDialog(SIDE_DIALOG);
                    setSelection(-1);
                    checkValidAndUpdateMaterialDiff();
                    break;
                case CLEAR_BOARD: {
                    Position pos = new Position();
                    cb.setPosition(pos);
                    setSelection(-1);
                    checkValidAndUpdateMaterialDiff();
                    break;
                }
                case INITIAL_POS: {
                    try {
                        Position pos = TextIO.readFEN(TextIO.startPosFEN);
                        cb.setPosition(pos);
                        setSelection(-1);
                        checkValidAndUpdateMaterialDiff();
                    } catch (ChessParseError e) {
                    }
                    break;
                }
                case CASTLING_FLAGS:
                    removeDialog(CASTLE_DIALOG);
                    showDialog(CASTLE_DIALOG);
                    setSelection(-1);
                    checkValidAndUpdateMaterialDiff();
                    break;
                case EN_PASSANT_FILE:
                    removeDialog(EP_DIALOG);
                    showDialog(EP_DIALOG);
                    setSelection(-1);
                    checkValidAndUpdateMaterialDiff();
                    break;
                case MOVE_COUNTERS:
                    removeDialog(MOVCNT_DIALOG);
                    showDialog(MOVCNT_DIALOG);
                    setSelection(-1);
                    checkValidAndUpdateMaterialDiff();
                    break;
                case COPY_POSITION: {
                    setPosFields();
                    String fen = TextIO.toFEN(cb.pos) + "\n";
                    ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                    clipboard.setText(fen);
                    setSelection(-1);
                    break;
                }
                case PASTE_POSITION: {
                    ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                    if (clipboard.hasText()) {
                        String fen = clipboard.getText().toString();
                        setFEN(fen);
                    }
                    break;
                }
                case GET_FEN:
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.setType("application/x-chess-fen");
                    try {
                        startActivityForResult(i, RESULT_GET_FEN);
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
        AlertDialog alert = builder.create();
        return alert;
    }
    case SIDE_DIALOG: {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.select_side_to_move_first);
        final int selectedItem = (cb.pos.whiteMove) ? 0 : 1;
        builder.setSingleChoiceItems(new String[] { getString(R.string.white), getString(R.string.black) },
                selectedItem, new Dialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        if (id == 0) { // white to move
                            cb.pos.setWhiteMove(true);
                            checkValidAndUpdateMaterialDiff();
                            dialog.cancel();
                        } else {
                            cb.pos.setWhiteMove(false);
                            checkValidAndUpdateMaterialDiff();
                            dialog.cancel();
                        }
                    }
                });
        AlertDialog alert = builder.create();
        return alert;
    }
    case CASTLE_DIALOG: {
        final CharSequence[] items = { getString(R.string.white_king_castle),
                getString(R.string.white_queen_castle), getString(R.string.black_king_castle),
                getString(R.string.black_queen_castle) };
        boolean[] checkedItems = { cb.pos.h1Castle(), cb.pos.a1Castle(), cb.pos.h8Castle(), cb.pos.a8Castle() };
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.castling_flags);
        builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                Position pos = new Position(cb.pos);
                boolean a1Castle = pos.a1Castle();
                boolean h1Castle = pos.h1Castle();
                boolean a8Castle = pos.a8Castle();
                boolean h8Castle = pos.h8Castle();
                switch (which) {
                case 0:
                    h1Castle = isChecked;
                    break;
                case 1:
                    a1Castle = isChecked;
                    break;
                case 2:
                    h8Castle = isChecked;
                    break;
                case 3:
                    a8Castle = isChecked;
                    break;
                }
                int castleMask = 0;
                if (a1Castle)
                    castleMask |= 1 << Position.A1_CASTLE;
                if (h1Castle)
                    castleMask |= 1 << Position.H1_CASTLE;
                if (a8Castle)
                    castleMask |= 1 << Position.A8_CASTLE;
                if (h8Castle)
                    castleMask |= 1 << Position.H8_CASTLE;
                pos.setCastleMask(castleMask);
                cb.setPosition(pos);
                checkValidAndUpdateMaterialDiff();
            }
        });
        AlertDialog alert = builder.create();
        return alert;
    }
    case EP_DIALOG: {
        final CharSequence[] items = { "A", "B", "C", "D", "E", "F", "G", "H", getString(R.string.none) };
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.select_en_passant_file);
        builder.setSingleChoiceItems(items, getEPFile(), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                setEPFile(item);
                dialog.cancel();
            }
        });
        AlertDialog alert = builder.create();
        return alert;
    }
    case MOVCNT_DIALOG: {
        View content = View.inflate(this, R.layout.edit_move_counters, null);
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setView(content);
        builder.setTitle(R.string.edit_move_counters);
        final EditText halfMoveClock = (EditText) content.findViewById(R.id.ed_cnt_halfmove);
        final EditText fullMoveCounter = (EditText) content.findViewById(R.id.ed_cnt_fullmove);
        halfMoveClock.setText(String.format(Locale.US, "%d", cb.pos.halfMoveClock));
        fullMoveCounter.setText(String.format(Locale.US, "%d", cb.pos.fullMoveCounter));
        final Runnable setCounters = new Runnable() {
            public void run() {
                try {
                    int halfClock = Integer.parseInt(halfMoveClock.getText().toString());
                    int fullCount = Integer.parseInt(fullMoveCounter.getText().toString());
                    cb.pos.halfMoveClock = halfClock;
                    cb.pos.fullMoveCounter = fullCount;
                } catch (NumberFormatException nfe) {
                    Toast.makeText(getApplicationContext(), R.string.invalid_number_format, Toast.LENGTH_SHORT)
                            .show();
                }
            }
        };
        builder.setPositiveButton("Ok", new Dialog.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                setCounters.run();
            }
        });
        builder.setNegativeButton("Cancel", null);

        final Dialog dialog = builder.create();

        fullMoveCounter.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    setCounters.run();
                    dialog.cancel();
                    return true;
                }
                return false;
            }
        });
        return dialog;
    }
    }
    return null;
}

From source file:com.willhauck.linconnectclient.SettingsActivity.java

@SuppressLint("SimpleDateFormat")
private void setupSimplePreferencesScreen() {
    // Load preferences
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this);

    // Add preferences from XML
    addPreferencesFromResource(R.xml.pref_general);
    bindPreferenceSummaryToValue(findPreference("pref_ip"));

    // Preference Categories
    serverCategory = ((PreferenceCategory) findPreference("cat_servers"));

    // Preferences
    refreshPreference = ((Preference) findPreference("pref_refresh"));
    serverCategory.removePreference(refreshPreference);

    loadingPreference = ((Preference) findPreference("pref_loading"));
    serverCategory.removePreference(loadingPreference);

    Preference prefEnable = findPreference("pref_enable");
    prefEnable.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override//from  w  w w.  ja va  2  s.  c  o m
        public boolean onPreferenceClick(Preference arg0) {
            // If Android 4.3+, open Notification Listener settings,
            // otherwise open accessibility settings
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
                startActivityForResult(new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS), 0);
            } else {
                Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
                startActivity(intent);
            }
            return true;
        }
    });

    ((Preference) findPreference("pref_ip")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference arg0, Object arg1) {
            // Update Custom IP address summary
            arg0.setSummary((String) arg1);

            refreshServerList();

            // Create and send test notification
            SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
            Object[] notif = new Object[3];
            notif[0] = "Hello from Android!";
            notif[1] = "Test succesful @ " + sf.format(new Date());
            notif[2] = SettingsActivity.this.getResources().getDrawable(R.drawable.ic_launcher);
            new TestTask().execute(notif);

            return true;
        }
    });

    Preference prefDownload = findPreference("pref_download");
    prefDownload.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Create share dialog with server download URL
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT,
                    "Download LinConnect server @ https://github.com/hauckwill/linconnect-server");
            sendIntent.setType("text/plain");
            startActivity(sendIntent);
            return true;
        }
    });

    Preference prefApplication = findPreference("pref_application");
    prefApplication.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open application settings screen
            Intent intent = new Intent(getApplicationContext(), ApplicationSettingsActivity.class);

            startActivity(intent);
            return true;
        }
    });

    Preference prefDonateBitcoin = findPreference("pref_donate_btc");
    prefDonateBitcoin.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            try {
                // Open installed Bitcoin wallet if possible
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(
                        "bitcoin:1125MguyS1feaop99bCDPQG6ukUcMuvVBo?label=Will%20Hauck&message=Donation%20for%20LinConnect"));
                startActivity(intent);
            } catch (Exception e) {
                // Otherwise, show dialog with Bitcoin address
                EditText input = new EditText(SettingsActivity.this);
                input.setText("1125MguyS1feaop99bCDPQG6ukUcMuvVBo");
                input.setEnabled(false);

                new AlertDialog.Builder(SettingsActivity.this).setTitle("Bitcoin Address")
                        .setMessage(
                                "Please donate to the following Bitcoin address. Thank you for the support.")
                        .setView(input)
                        .setPositiveButton("Copy Address", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                                        Context.CLIPBOARD_SERVICE);
                                clipboard.setText("1125MguyS1feaop99bCDPQG6ukUcMuvVBo");
                            }
                        }).setNegativeButton("Okay", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                            }
                        }).show();
            }
            return true;
        }
    });

    Preference prefGooglePlus = findPreference("pref_google_plus");
    prefGooglePlus.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open Google Plus page
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("https://plus.google.com/114633032648182423928/posts"));
            startActivity(intent);
            return true;
        }
    });

    Preference prefDonatePlay = findPreference("pref_donate_play");
    prefDonatePlay.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open Donation Key app on Play Store
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=com.willhauck.donation"));
            startActivity(intent);
            return true;
        }
    });

    // Create handler to process a detected server
    serverFoundHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.obj != null) {

                javax.jmdns.ServiceInfo serviceInfo = mJmDNS.getServiceInfo(jmDnsServiceType, (String) msg.obj);

                // Get info about server
                String name = serviceInfo.getName();
                String port = String.valueOf(serviceInfo.getPort());
                String ip = serviceInfo.getHostAddresses()[0];

                // Create a preference representing the server
                Preference p = new Preference(SettingsActivity.this);
                p.setTitle(name);
                p.setSummary(ip + ":" + port);

                p.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference arg0) {
                        refreshServerList();

                        // Save IP address in preferences
                        Editor e = sharedPreferences.edit();
                        e.putString("pref_ip", arg0.getSummary().toString());
                        e.apply();

                        // Create and send test notification
                        SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");

                        Object[] notif = new Object[3];
                        notif[0] = "Hello from Android!";
                        notif[1] = "Test succesful @ " + sf.format(new Date());
                        notif[2] = SettingsActivity.this.getResources().getDrawable(R.drawable.ic_launcher);

                        new TestTask().execute(notif);

                        return true;
                    }

                });

                // Add preference to server list if it doesn't already exist
                boolean found = false;
                for (int i = 0; i < serverCategory.getPreferenceCount(); i++) {
                    if (serverCategory.getPreference(i) != null
                            && serverCategory.getPreference(i).getTitle() != null
                            && serverCategory.getPreference(i).getTitle().equals(p.getTitle())) {
                        found = true;
                    }
                }
                if (!found) {
                    serverCategory.addPreference(p);
                }

                refreshServerList();

                // Remove loading indicator, add refresh indicator if it
                // isn't already there
                if (findPreference("pref_loading") != null)
                    serverCategory.removePreference(findPreference("pref_loading"));
                if (findPreference("pref_refresh") == null)
                    serverCategory.addPreference(refreshPreference);

            }
            return true;
        }
    });

    // Create task to scan for servers
    class ServerScanTask extends AsyncTask<String, ServiceEvent, Boolean> {

        @Override
        protected void onPreExecute() {
            // Remove refresh preference, add loading preference
            if (findPreference("pref_refresh") != null)
                serverCategory.removePreference(refreshPreference);
            serverCategory.addPreference(loadingPreference);

            try {
                mJmDNS.removeServiceListener(jmDnsServiceType, ServerListener);
            } catch (Exception e) {
            }

            refreshServerList();

        }

        @Override
        protected Boolean doInBackground(String... notif) {
            WifiInfo wifiinfo = mWifiManager.getConnectionInfo();
            int intaddr = wifiinfo.getIpAddress();

            // Ensure there is an active Wifi connection
            if (intaddr != 0) {
                byte[] byteaddr = new byte[] { (byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff),
                        (byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff) };
                InetAddress addr = null;
                try {
                    addr = InetAddress.getByAddress(byteaddr);
                } catch (UnknownHostException e1) {
                }

                // Create Multicast lock (required for JmDNS)
                mMulticastLock = mWifiManager.createMulticastLock("LinConnect");
                mMulticastLock.setReferenceCounted(true);
                mMulticastLock.acquire();

                try {
                    mJmDNS = JmDNS.create(addr, "LinConnect");
                } catch (IOException e) {
                }

                // Create listener for detected servers
                ServerListener = new ServiceListener() {

                    @Override
                    public void serviceAdded(ServiceEvent arg0) {
                        final String name = arg0.getName();
                        // Send the server data to the handler, delayed by
                        // 500ms to ensure all information is read
                        serverFoundHandler.sendMessageDelayed(Message.obtain(serverFoundHandler, -1, name),
                                500);
                    }

                    @Override
                    public void serviceRemoved(ServiceEvent arg0) {
                    }

                    @Override
                    public void serviceResolved(ServiceEvent arg0) {
                        mJmDNS.requestServiceInfo(arg0.getType(), arg0.getName(), 1);
                    }
                };
                mJmDNS.addServiceListener(jmDnsServiceType, ServerListener);

                return true;
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (!result) {
                // Notify user if there is no connection
                if (findPreference("pref_loading") != null) {
                    serverCategory.removePreference(findPreference("pref_loading"));
                    serverCategory.addPreference(refreshPreference);

                }
                Toast.makeText(getApplicationContext(), "Error: no connection.", Toast.LENGTH_LONG).show();
            }
        }
    }

    refreshPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference arg0) {
            new ServerScanTask().execute();
            return true;
        }

    });

    // Start scanning for servers
    new ServerScanTask().execute();
}

From source file:com.ryan.ryanreader.fragments.CommentListingFragment.java

@Override
public boolean onContextItemSelected(MenuItem item) {

    final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

    if (info.position <= 0)
        return false;

    final Action action = Action.values()[item.getItemId()];
    final RedditPreparedComment comment = (RedditPreparedComment) lv.getAdapter().getItem(info.position);

    switch (action) {

    case UPVOTE:/* w w  w. j  av a2  s.c  o  m*/
        comment.action(getSupportActivity(), RedditAPI.RedditAction.UPVOTE);
        break;

    case DOWNVOTE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.DOWNVOTE);
        break;

    case UNVOTE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.UNVOTE);
        break;

    case REPORT:

        new AlertDialog.Builder(getSupportActivity()).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        comment.action(getSupportActivity(), RedditAPI.RedditAction.REPORT);
                        // TODO update the view to show the result
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case REPLY: {
        final Intent intent = new Intent(getSupportActivity(), CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", comment.idAndType);
        startActivity(intent);
        break;
    }

    case EDIT: {
        final Intent intent = new Intent(getSupportActivity(), CommentEditActivity.class);
        intent.putExtra("commentIdAndType", comment.idAndType);
        intent.putExtra("commentText", comment.src.body);
        startActivity(intent);
        break;
    }

    case COMMENT_LINKS:
        final HashSet<String> linksInComment = comment.computeAllLinks();

        if (linksInComment.isEmpty()) {
            General.quickToast(getSupportActivity(), R.string.error_toast_no_urls_in_comment);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(getSupportActivity());
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(getSupportActivity(), linksArr[which], false);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_comment_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;

    case SHARE:

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comment by " + comment.src.author + " on Reddit");

        // TODO this currently just dumps the markdown
        mailer.putExtra(Intent.EXTRA_TEXT, StringEscapeUtils.unescapeHtml4(comment.src.body));
        startActivityForResult(Intent.createChooser(mailer, context.getString(R.string.action_share)), 1);

        break;

    case COPY:

        ClipboardManager manager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        // TODO this currently just dumps the markdown
        manager.setText(StringEscapeUtils.unescapeHtml4(comment.src.body));
        break;

    case COLLAPSE:
        if (comment.getBoundView() != null)
            handleCommentVisibilityToggle(comment.getBoundView());
        break;

    case USER_PROFILE:
        UserProfileDialog.newInstance(comment.src.author).show(getSupportActivity());
        break;

    case PROPERTIES:
        CommentPropertiesDialog.newInstance(comment.src).show(getSupportActivity());
        break;

    }

    return true;
}

From source file:org.lol.reddit.fragments.CommentListingFragment.java

@Override
public boolean onContextItemSelected(MenuItem item) {

    final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

    if (info.position <= 0) {
        return false;
    }//from   w  ww.j av  a2  s. c o m

    final Object selectedObject = lv.getAdapter().getItem(info.position);

    if (!(selectedObject instanceof RedditCommentListItem)
            || !((RedditCommentListItem) selectedObject).isComment()) {
        return false;
    }

    final Action action = Action.values()[item.getItemId()];
    final RedditPreparedComment comment = ((RedditCommentListItem) selectedObject).asComment();

    switch (action) {

    case UPVOTE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.UPVOTE);
        break;

    case DOWNVOTE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.DOWNVOTE);
        break;

    case UNVOTE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.UNVOTE);
        break;

    case SAVE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.SAVE);
        break;

    case UNSAVE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.UNSAVE);
        break;

    case REPORT:

        new AlertDialog.Builder(getSupportActivity()).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        comment.action(getSupportActivity(), RedditAPI.RedditAction.REPORT);
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case REPLY: {
        final Intent intent = new Intent(getSupportActivity(), CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", comment.idAndType);
        startActivity(intent);
        break;
    }

    case EDIT: {
        final Intent intent = new Intent(getSupportActivity(), CommentEditActivity.class);
        intent.putExtra("commentIdAndType", comment.idAndType);
        intent.putExtra("commentText", StringEscapeUtils.unescapeHtml4(comment.src.body));
        startActivity(intent);
        break;
    }

    case COMMENT_LINKS:
        final HashSet<String> linksInComment = comment.computeAllLinks();

        if (linksInComment.isEmpty()) {
            General.quickToast(getSupportActivity(), R.string.error_toast_no_urls_in_comment);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(getSupportActivity());
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(getSupportActivity(), linksArr[which], false);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_comment_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;

    case SHARE:

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comment by " + comment.src.author + " on Reddit");

        // TODO this currently just dumps the markdown
        mailer.putExtra(Intent.EXTRA_TEXT, StringEscapeUtils.unescapeHtml4(comment.src.body));
        startActivityForResult(
                Intent.createChooser(mailer, getSupportActivity().getString(R.string.action_share)), 1);

        break;

    case COPY:

        ClipboardManager manager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        // TODO this currently just dumps the markdown
        manager.setText(StringEscapeUtils.unescapeHtml4(comment.src.body));
        break;

    case COLLAPSE:
        if (comment.getBoundView() != null) {
            handleCommentVisibilityToggle(comment.getBoundView());
        } else {
            General.quickToast(getSupportActivity(), "Error: Comment is no longer visible.");
        }
        break;

    case USER_PROFILE:
        LinkHandler.onLinkClicked(getSupportActivity(), new UserProfileURL(comment.src.author).toString());
        break;

    case PROPERTIES:
        CommentPropertiesDialog.newInstance(comment.src).show(getSupportActivity());
        break;

    case GO_TO_COMMENT: {
        PostCommentListingURL url = new PostCommentListingURL(null, comment.src.link_id, comment.idAlone, null,
                null, null);
        LinkHandler.onLinkClicked(getSupportActivity(), url.toString());
        break;
    }

    case CONTEXT: {
        PostCommentListingURL url = new PostCommentListingURL(null, comment.src.link_id, comment.idAlone, 3,
                null, null);
        LinkHandler.onLinkClicked(getSupportActivity(), url.toString());
        break;
    }
    }

    return true;
}

From source file:org.liberty.android.fantastischmemo.ui.QACardActivity.java

protected void copyToClipboard() {
    String copiedText = "";
    switch (option.getCopyClipboard()) {
    case QUESTION:
        copiedText = "" + currentCard.getQuestion();
        break;//  ww  w .j a  va 2  s.  c  om
    case ANSWER:
        copiedText = "" + currentCard.getAnswer();
        break;
    case BOTH:
        copiedText = "" + currentCard.getQuestion() + " " + currentCard.getAnswer();
        break;
    default:
        copiedText = "";
    }
    if (!Strings.isNullOrEmpty(copiedText)) {
        ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        // Some Samsung device doesn't have ClipboardManager. So check
        // the null here to prevent crash.
        if (cm != null) {
            try {
                cm.setText(copiedText);
            } catch (NullPointerException npe) {
                // This is a Samsung clipboard bug. setPrimaryClip() can throw
                // a NullPointerException if Samsung's /data/clipboard directory is full.
                // Fortunately, the text is still successfully copied to the clipboard.
                Ln.e(npe, "Got null pointer exception when copying text to clipboard");
            }
        }
    }
}

From source file:net.gsantner.opoc.util.ShareUtil.java

/***
 * Replace (primary) clipboard contents with given {@code text}
 * @param text Text to be set/*  w w w. j a  v  a  2s .  co  m*/
 */
public boolean setClipboard(CharSequence text) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager cm = ((android.text.ClipboardManager) _context
                .getSystemService(Context.CLIPBOARD_SERVICE));
        if (cm != null) {
            cm.setText(text);
            return true;
        }
    } else {
        android.content.ClipboardManager cm = ((android.content.ClipboardManager) _context
                .getSystemService(Context.CLIPBOARD_SERVICE));
        if (cm != null) {
            ClipData clip = ClipData.newPlainText(_context.getPackageName(), text);
            cm.setPrimaryClip(clip);
            return true;
        }
    }
    return false;
}

From source file:me.myatminsoe.myansms.MessageListActivity.java

/**
 * {@inheritDoc}//w w  w .  ja  v a2s .co  m
 */
public final boolean onItemLongClick(final AdapterView<?> parent, final View view, final int position,
        final long id) {
    final Context context = this;
    final Message m = Message.getMessage(this, (Cursor) parent.getItemAtPosition(position));
    final Uri target = m.getUri();
    final int read = m.getRead();
    final int type = m.getType();
    Builder builder = new Builder(context);
    builder.setTitle(R.string.message_options_);

    final Contact contact = conv.getContact();
    final String a = contact.getNumber();
    final String n = contact.getName();

    String[] items = longItemClickDialog;
    if (TextUtils.isEmpty(n)) {
        items[WHICH_VIEW_CONTACT] = getString(R.string.add_contact_);
    } else {
        items[WHICH_VIEW_CONTACT] = getString(R.string.view_contact_);
    }
    items[WHICH_CALL] = getString(R.string.call) + " " + contact.getDisplayName();
    if (read == 0) {
        items = items.clone();
        items[WHICH_MARK_UNREAD] = context.getString(R.string.mark_read_);
    }
    if (type == Message.SMS_DRAFT) {
        items = items.clone();
        items[WHICH_FORWARD] = context.getString(R.string.send_draft_);
    }
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @SuppressWarnings("deprecation")
        @Override
        public void onClick(final DialogInterface dialog, final int which) {
            Intent i;
            switch (which) {
            case WHICH_VIEW_CONTACT:
                if (n == null) {
                    i = ContactsWrapper.getInstance().getInsertPickIntent(a);
                    Conversation.flushCache();
                } else {
                    final Uri u = MessageListActivity.this.conv.getContact().getUri();
                    i = new Intent(Intent.ACTION_VIEW, u);
                }
                try {
                    MessageListActivity.this.startActivity(i);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(MessageListActivity.this, R.string.error_unknown, Toast.LENGTH_LONG).show();
                }
                break;
            case WHICH_CALL:
                MessageListActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("tel:" + a)));
                break;
            case WHICH_MARK_UNREAD:
                ConversationListActivity.markRead(context, target, 1 - read);
                MessageListActivity.this.markedUnread = true;
                break;
            case WHICH_REPLY:
                MessageListActivity.this.startActivity(
                        ConversationListActivity.getComposeIntent(MessageListActivity.this, a, false));
                break;
            case WHICH_FORWARD:
                int resId;
                if (type == Message.SMS_DRAFT) {
                    resId = R.string.send_draft_;
                    i = ConversationListActivity.getComposeIntent(MessageListActivity.this,
                            MessageListActivity.this.conv.getContact().getNumber(), false);
                } else {
                    resId = R.string.forward_;
                    i = new Intent(Intent.ACTION_SEND);
                    i.setType("text/plain");
                    i.putExtra("forwarded_message", true);
                }
                CharSequence text;
                if (PreferencesActivity.decodeDecimalNCR(context)) {
                    text = Converter.convertDecNCR2Char(m.getBody());
                } else {
                    text = m.getBody();
                }
                i.putExtra(Intent.EXTRA_TEXT, text);
                i.putExtra("sms_body", text);
                context.startActivity(Intent.createChooser(i, context.getString(resId)));
                break;
            case WHICH_COPY_TEXT:
                final ClipboardManager cm = (ClipboardManager) context
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                if (PreferencesActivity.decodeDecimalNCR(context)) {
                    cm.setText(Converter.convertDecNCR2Char(m.getBody()));
                } else {
                    cm.setText(m.getBody());
                }
                break;
            case WHICH_VIEW_DETAILS:
                final int t = m.getType();
                Builder b = new Builder(context);
                b.setTitle(R.string.view_details_);
                b.setCancelable(true);
                StringBuilder sb = new StringBuilder();
                final String a = m.getAddress(context);
                final long d = m.getDate();
                final String ds = DateFormat.format(context.getString(R.string.DATEFORMAT_details), d)
                        .toString();
                String sentReceived;
                String fromTo;
                if (t == Calls.INCOMING_TYPE) {
                    sentReceived = context.getString(R.string.received_);
                    fromTo = context.getString(R.string.from_);
                } else if (t == Calls.OUTGOING_TYPE) {
                    sentReceived = context.getString(R.string.sent_);
                    fromTo = context.getString(R.string.to_);
                } else {
                    sentReceived = "ukwn:";
                    fromTo = "ukwn:";
                }
                sb.append(sentReceived).append(" ");
                sb.append(ds);
                sb.append("\n");
                sb.append(fromTo).append(" ");
                sb.append(a);
                sb.append("\n");
                sb.append(context.getString(R.string.type_));
                if (m.isMMS()) {
                    sb.append(" MMS");
                } else {
                    sb.append(" SMS");
                }
                b.setMessage(sb.toString());
                b.setPositiveButton(android.R.string.ok, null);
                b.show();
                break;
            case WHICH_DELETE:
                ConversationListActivity.deleteMessages(context, target, R.string.delete_message_,
                        R.string.delete_message_question, null);
                break;
            default:
                break;
            }
        }
    });
    builder.show();
    return true;
}