2

I encountered a strange "problem" or maybe a "bug" in Android. I use the ClipboardManager for my App quite often. But if I use it within some seconds twice, I always get a NullPointerException. What I think is that I Clipboard is notalready filled when I am accessing it but this seems to be a really silly idea... Has anyone encountered the same problem, or am I doing something wrong? I get the error at String text = item.getText().toString();

Error message:

java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference at at.co.netconsulting.leotranslater.SettingsActivity$1$3.onPrimaryClipChanged

Thanks for every hint or help in advance!

Here is a piece of my code:

final ClipboardManager myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                    myClipboard.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener() {
                        @Override
                        public void onPrimaryClipChanged() {
                            ClipData cp = myClipboard.getPrimaryClip();
                            if(cp.getItemCount()>0) {
                                ClipData.Item item = cp.getItemAt(0);
                                if (item == null) {
                                    Toast.makeText(getApplicationContext(), "Item is null", Toast.LENGTH_LONG).show();
                                } else {
                                    if(item!=null) {
                                        String text = item.getText().toString();
                                        Toast.makeText(getApplicationContext(), "Sie suchen nach dem Wort: " + text, Toast.LENGTH_LONG).show();
                                        Intent msgIntent = new Intent(SettingsActivity.this, ServiceTranslator.class);
                                        msgIntent.putExtra("ClipBoardData", text);
                                        startService(msgIntent);
                                    }
                                }
                            }
                        }
                    });
                }
Bernd
  • 593
  • 2
  • 8
  • 31

1 Answers1

1

I think this could be the solution.

String text = item.coerceToText(getBaseContext()).toString();

Looking into the documentation, it is said that if all you want is the textual representation of the clipped data, you * can use the convenience method {@link Item#coerceToText Item.coerceToText}.

I hope that will solve my problem!

Bernd
  • 593
  • 2
  • 8
  • 31