AsyncTask: ClassCastException: java.lang.Object[] 不能转换为 java.lang.String[] [英] AsyncTask: ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]
问题描述
在我的应用程序中,我为 gcm ccs(xmpp) 运行这些代码,代码显示以下错误 An error occurred while execution doinbackground.excute()
这是代码:
In my application I run these code for gcm ccs(xmpp) and the code shows following error An error occurred while executing doinbackground.excute()
This is the code:
sendTask = new AsyncTask<String, String, String>() {
protected String doInBackground(String... title) {
Bundle data = new Bundle();
data.putString("ACTION", action);
data.putString("CLIENT_MESSAGE", "Hello GCM CCS XMPP!");
String id = Integer.toString(ccsMsgId.incrementAndGet());
try {
Log.d("RegisterActivity", "messageid: " + id);
gcm.send(SENDER_ID + "@gcm.googleapis.com", id,
data);
Log.d("RegisterActivity", "After gcm.send successful.");
} catch (IOException e) {
Log.d("RegisterActivity", "Exception: " + e);
e.printStackTrace();
}
return "Sent message.";
}
protected void onPostExecute(String result) {
sendTask = null;
// tosat about the success in return
}
};
sendTask.execute(null, null, null);
推荐答案
你的 sendTask
是如何声明的?我想它只是AsyncTask sendTask;
,如果是,则将其更改为:
How is your sendTask
declared? I suppose its simply AsyncTask sendTask;
, if so then change it to:
AsyncTask<String, String, String> sendTask;
<小时>
这个异常的原因类似于下面代码中发生的那个:
The cause of this exception is similar to the one that occurs in below code:
Object arr1[] = new Object[] {null,null,null};
String arr2[] = (String[])arr1; // here java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
Java 中的 VarArgs 是作为数组实现的,因此当您将 sendTask 声明为 AsyncTask
时,编译器将使用 new 调用您的
,但是当你将它声明为 doInBackground
String[]{null,null,null}AsyncTask
然后 doInBackground
用 new Object[]{null> 调用,null,null}
.
VarArgs in java are implemented as arrays, so when you declare sendTask as AsyncTask<String, String, String>
then compiler will call your doInBackground
with new String[]{null,null,null}
, but when you declare it as AsyncTask
then doInBackground
is called with new Object[]{null,null,null}
.
由于类型擦除,编译器会添加从 Object[]
到 String[]
的隐藏隐式转换.这是为了让以下代码正常工作:
Because of type erasure, compiler will add hidden implicit cast from Object[]
to String[]
. This is to allow code as below to work correctly:
AsyncTask sendTask = ...;
Object[] arg = new String[]{null,null,null};
sendTask.execute(arg);
这篇关于AsyncTask: ClassCastException: java.lang.Object[] 不能转换为 java.lang.String[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!