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

后端 未结 2 1482
花落未央
花落未央 2021-01-13 20:53

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 co

相关标签:
2条回答
  • 2021-01-13 21:07

    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);
    
    0 讨论(0)
  • 2021-01-13 21:12

    Try

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

    instead of

    sendTask.execute(null, null, null);
    
    0 讨论(0)
提交回复
热议问题