将android.support.v4.app.FragmentActivity $ NonConfigurationInstances转换为我的AsyncTask时出错

时间:2015-10-17 08:10:39

标签: java android types casting

我遇到了代码行问题:

mt=(MyTask)getLastNonConfigurationInstance();

mt是MyTask类的实例

static class MyTask extends AsyncTask<String,Integer,Void>
    {
        MainActivity activity;
        void link (MainActivity act)
        {
            activity=act;
        }
        void unlink()
        {

            activity=null;
        }

        @Override
        protected Void doInBackground(String... params) {

            try{
                for(int i=1;i<=10;i++){
                    TimeUnit.SECONDS.sleep(1);
                    publishProgress(i);
                    Log.d("qwe", "i = " + i
                            + ", MyTask: " + this.hashCode()
                            + ", MainActivity: " + activity.hashCode());

                }
            }
            catch (InterruptedException ie)
            {
                ie.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            activity.tv.setText("i = "+values[0]);
        }
    }

并将其保存在onRetainCustomNonConfigurationInstance方法

  @Override
    public Object onRetainCustomNonConfigurationInstance() {
        mt.unlink();
        return mt;
    }

错误当我尝试将值从配置实例传递到mt时到达,错误消息为

  

java.lang.ClassCastException:   android.support.v4.app.FragmentActivity $ NonConfigurationInstances   无法施展   com.example.bermud06.p091_asynctaskdisplayrotate.MainActivity $ MyTask

使用API​​等级为22的nexus 5设备。

1 个答案:

答案 0 :(得分:1)

请改用getLastCustomNonConfigurationInstance()。来自FragmentActivity的文档:

  

<强> public Object onRetainCustomNonConfigurationInstance()

     

使用此代替onRetainNonConfigurationInstance()。稍后检索   与getLastCustomNonConfigurationInstance()