Android ClassCastException Object [] to String []

时间:2016-01-20 17:28:29

标签: android classcastexception

嘿其他程序员< 3
我想通过broadcastReceiver将我的服务中的字符串数组传输到我的MainActivity  字符串数组包含在Intent中  但是当我试图从我的意图中获取String []时  然后它是一个对象数组,我不能只使用intent.getStringArrayExtra(String)  然后我尝试了这个:

如何在Java中将对象数组转换为字符串数组? String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);

但它仍然可以工作:/

public class MainActivity extends Activity implements View.OnClickListener {
final String LOG_TAG = "mainActivityLogs";
Button btnStartService;

private int numberOfFinishedTasks = 0;
private List<String> finishedTasksInTheLast60Sec = new ArrayList<>();
private int startedTasks = 0;
private ProgressBar pbService;
private Handler progressHandler = new Handler();

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        //results in java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]
        finishedTasksInTheLast60Sec = Arrays.asList(intent.getStringArrayExtra("finishedTasks"));

        //results in java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]
        Object[] objectArray = intent.getStringArrayExtra("finishedTasks");
        String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
        finishedTasksInTheLast60Sec = Arrays.asList(stringArray);

        numberOfFinishedTasks += finishedTasksInTheLast60Sec.size();
        for (String finishedTask : finishedTasksInTheLast60Sec) {
            Log.d(LOG_TAG, finishedTask);
        }
    }
};

此函数在Service文件MyService中,var finishedTasks只包含已关闭的Threads的名称:

   private void sendBroadcast(List<String> finishedTasks) {
   Intent intent = new Intent("myServiceUpdate");
   intent.putExtra("finishedTasks", finishedTasks.toArray());
   LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
   }

我希望你能提供帮助,如果你需要整个代码,请发短信给我:)

1 个答案:

答案 0 :(得分:2)

发送时,将List类型转换为ArrayList类型:

intent.putStringArrayListExtra("finishedTasks",(ArrayList<String>)finishedTasks);

接收时只需通过以下方式获取数据:

 List stringList = getIntent().getStringArrayListExtra("finishedTasks");