Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

android - AsyncTask: ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

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}.

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...