3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

選択したテキストでWeb検索を実施する際にハマったこと

Posted at

Intent.ACTION_WEB_SEARCHを使用して、Web検索を簡単に実装することができます。
典型的なコードは以下のような感じになるかと思います。

CharSequence selectedText = textView.getText()
        .subSequence(textView.getSelectionStart(), textView.getSelectionEnd());
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, selectedText);
startActivity(intent);

しかしこのコード、コンパイルこそ通るものの正常に動作しません。Google検索は起動されるが、選択したテキストによる検索が実行されないまま止まってしまうのです。

なんでかなあ〜?としばらくハマってしまったんですが、原因はintent.putExtraで渡す引数です。
1行目を以下のように修正すれば正常に動作しました。

String selectedText = textView.getText()
        .subSequence(textView.getSelectionStart(), textView.getSelectionEnd())
        .toString();
...

要するにintent.putExtraにはCharSequenceではなくStringを渡さなければならないということです。CharSequenceも渡せるし、String implements CharSequenceなので問題ないと思い込んでました・・・。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?