0

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

Karim O.
  • 1,325
  • 6
  • 22
  • 36
  • You should post the stacktrace from the crash so we can better help you help yourself – codeMagic Jan 01 '16 at 23:06
  • `ClipData.getItemCount()` this returns `null` when you click on button. Debug your code. – Anand Singh Jan 01 '16 at 23:13
  • public String getTextFromClipboard(){ String text=""; ClipboardManager myClipboard; myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); ClipData clipData = null; if (myClipboard != null) { clipData = myClipboard.getPrimaryClip(); if (clipData!=null&&clipData.getItemCount()>0){ ClipData.Item item = clipData.getItemAt(0); text = item.getText().toString(); } } return text; } – Sunil Apr 23 '18 at 11:03

1 Answers1

0

Fixed it. Needed to handle cData if it was null.

Karim O.
  • 1,325
  • 6
  • 22
  • 36