Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't get why this ClassCastException occurs

Tags:

// Application ... Intent i = new Intent(); i.putExtra(EXTRA_FILE_UPLOAD_URIS, mGalleryAdapter.getItems());   Uri[] getItems() { return mItems; }  // Service ... intent.getParcelableArrayExtra(EXTRA_FILE_UPLOAD_URIS); //works, returns Parcelable[] Uri[] uris = (Uri[])intent.getParcelableArrayExtra(EXTRA_FILE_UPLOAD_URIS); // ... Breaks with ClassCastException 

Why does the cast to Uri[] break, when Uri is Parcelable?

like image 970
Tom Fobear Avatar asked Jan 05 '12 16:01

Tom Fobear


People also ask

What causes ClassCastException?

ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another. It's thrown to indicate that the code has attempted to cast an object to a related class, but of which it is not an instance.

How do you avoid ClassCastException?

To prevent the ClassCastException exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type.

How do I resolve Java Lang ClassCastException error?

// type cast an parent type to its child type. In order to deal with ClassCastException be careful that when you're trying to typecast an object of a class into another class ensure that the new type belongs to one of its parent classes or do not try to typecast a parent object to its child type.

Which method throws ClassCastException?

A class cast exception is thrown by Java when you try to cast an Object of one data type to another.


1 Answers

Use this method, it work for me.

Parcelable[] ps = getIntent().getParcelableArrayExtra(); Uri[] uri = new Uri[ps.length]; System.arraycopy(ps, 0, uri, 0, ps.length); 
like image 131
solo Avatar answered Oct 09 '22 18:10

solo