5

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);
dragosht
  • 3,237
  • 2
  • 23
  • 32
Alka Nigam
  • 61
  • 1
  • 3
  • 1
    Why arent you calling simply sendTask.execute(); – Rick Sanchez Dec 21 '15 at 16:23
  • while the exception is the same as in http://stackoverflow.com/questions/15264182/classcastexception-java-lang-object-cannot-be-cast-to-java-lang-string-andr, the context and the reason why it is generated is different. – marcinj Dec 21 '15 at 18:41

2 Answers2

15

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);
marcinj
  • 48,511
  • 9
  • 79
  • 100
0

Try

sendTask.execute(new String[]{""});

instead of

sendTask.execute(null, null, null);
SachinS
  • 2,223
  • 1
  • 15
  • 25