Error casting Object[] to ContentValues[]

早过忘川 提交于 2019-12-10 23:34:01

问题


I'm following a tutorial about content providers and, in a specific code, they inserted some data using a bulkInsert method. They also used a Vector variable (cVVector) to store all the ContentValues.

Code that was mentioned:

if (cVVector.size() > 0) {
   ContentValues[] cvArray = new ContentValues[cVVector.size()];
   cVVector.toArray(cvArray);
   mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
}

Then, I tried to reduce the code by casting cVVector.toArray() to ContentValues[], but I'm getting an error.

Code edited by me:

if (cVVector.size() > 0) {
   mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, (ContentValues[]) cVVector.toArray());
}

Error that I'm getting:

FATAL EXCEPTION: AsyncTask #1
Process: com.example.thiago.sunshine, PID: 9848
java.lang.RuntimeException: An error occured while executing doInBackground()
...
Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to android.content.ContentValues[]

Finally, my question is: Why I can't do a casting between an Object[] and a ContentValues[] ?

Obs.: English is not my mother tongue, please excuse any errors.


回答1:


You can't cast Object[] to ContentValues[], because there is no relationship between these two types. They are different array types.

Just like you can cast an Object to a String like this :

Object a = "aa";
String b = (String) a;

because String is a subclass of Object.

But you can't do this :

Object[] ar = new Object[]{"aa", "bb"};
String[] br = (String[]) ar;

You will find this is OK in compile time, but will not work in runtime. The forced type conversion in JAVA may only work for single object not array.

You can replace your code with:

if (cVVector.size() > 0) {
   mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, (ContentValues[]) cVVector.toArray(new ContentValues[1]));
}

Hope this can help you.



来源:https://stackoverflow.com/questions/38798196/error-casting-object-to-contentvalues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!