Basically I have a button on my activity that pastes text from the clipboard. My problem is that after testing it, the app crashes if there is nothing to paste from the clipboard (as in, nothing was copied to the clipboard). The paste function works if there is something in the clipboard, so I would like to know how to handle it. I tried handling this kind of crash but it doesn't work for me.
public void PasteText(View v)
{
TextView mainText = (TextView) findViewById(R.id.editext);
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData cData = clipboard.getPrimaryClip();
ClipData.Item item;
String text = "";
if(cData.getItemCount() > 0)
{
item = cData.getItemAt(0);
text = (String) item.getText();
mainText.append(text);
return;
}
else
{
item = null;
mainText.append(text);
return;
}
}
Logcat:
01-01 15:07:56.860: E/AndroidRuntime(10567): java.lang.IllegalStateException: Could not execute method of the activity
01-01 15:07:56.860: E/AndroidRuntime(10567): at android.view.View$1.onClick(View.java:4025)
01-01 15:07:56.860: E/AndroidRuntime(10567): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.ClipData.getItemCount()' on a null object reference
01-01 15:07:56.860: E/AndroidRuntime(10567): at com.karimo.tester.MainForm.PasteText(MainForm.java:109)
01-01 15:07:56.860: E/AndroidRuntime(10567): ... 13 more