安卓 AsyncTask:ClassCastException:java。lang.Object[]无法转换为java。lang.String[]
在我的应用程序中,我为gcm ccs(xmpp)运行了这些代码,代码显示了以下错误执行doinbackground.excute()
以下是代码:
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);
# 1 楼答案
试试看
sendTask.execute(new String[]{""});
而不是
# 2 楼答案
你的
sendTask
是如何声明的?我想它只是AsyncTask sendTask;
,如果是这样,那么将其更改为:此异常的原因与以下代码中出现的原因类似:
java中的vararg是作为数组实现的,所以当您将sendTask声明为
AsyncTask<String, String, String>
时,编译器将用new String[]{null,null,null}
调用doInBackground
,但当您将其声明为AsyncTask
时,则用new Object[]{null,null,null}
调用doInBackground
由于类型擦除,编译器将添加从
Object[]
到String[]
的隐藏隐式强制转换。这是为了让以下代码正常工作: