0

The following code is throwing a NullPointerException because the ArrayList isn't being converted to an Array correctly. The array is supposed to be passed to another activity. This works because I can pass a regular String[] but when I try to convert an ArrayList to Array I get the error. What's the right way to convert ArrayList to Array?

String[] tmpHtml = new String[(siteElements.size())];
tmpHtml = (String[]) siteElements.toArray();
Intent returnResult = new Intent();
returnResult.putExtra("elements", tmpHtml);
setResult(RESULT_OK, returnResult);
finish();
2
  • 1
    I would have expected a ClassCastException. toArray with no argument returns an Object[]. Commented Mar 14, 2013 at 1:35
  • Ahh yes it was a ClassCastException. Getting tired :) Commented Mar 14, 2013 at 1:38

2 Answers 2

3

The way you covert the ArrayList to String array was wrong. The correct way is:

tmpHtml = siteElements.toArray(tmpHtml);
Sign up to request clarification or add additional context in comments.

Comments

0

Changwei Yao's answer will work, but why not

// put to intent
returnResult.putStringArrayListExtra("elements", siteElements);
// Get from intent
returnResult.getStringArrayListExtra("elements");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.