AsyncTask:ClassCastException:java.lang.Object []无法强制转换为java.lang.String [] [英] AsyncTask: ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]

查看:124
本文介绍了AsyncTask:ClassCastException:java.lang.Object []无法强制转换为java.lang.String []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我为gcm ccs(xmpp)运行这些代码,代码显示以下错误执行时出错 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怎么样? / code>申报?我想它只是 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<时; String,String,String> 然后编译器将使用 new String []调用 doInBackground {null,null,null } ,但是当你将其声明为 AsyncTask 时,将使用<$ c调用doInBackground $ c> 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 [] 中隐藏的隐式强制转换添加到串[] 。这是为了允许以下代码正常工作:

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆