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);
}
}
}
}
});
}