当前位置: 首页 > 面试题库 >

java.lang.IllegalStateException:onSaveInstanceState之后无法执行此操作:-片段错误

高弘光
2023-03-14
问题内容

嗨,我用片段A,第二个片段用b。调用了b并使用了asynctask
方法,但是我第一次使用它是完美的,但是第二次使用它使应用程序崩溃,并且我的错误日志在以下:::我使用了Samsung平板电脑,但工作正常,但是Samsung
core mobile崩溃了。

E/AndroidRuntime: FATAL EXCEPTION: main
E/AndroidRuntime: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
E/AndroidRuntime:   at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1343)
E/AndroidRuntime:   at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1361)
E/AndroidRuntime:   at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
E/AndroidRuntime:   at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
E/AndroidRuntime:   at com.buymysari.fragment.SendImageServerFragment$SendImageServerTask.onPostExecute(SendImageServerFragment.java:158)
E/AndroidRuntime:   at com.buymysari.fragment.SendImageServerFragment$SendImageServerTask.onPostExecute(SendImageServerFragment.java:1)
E/AndroidRuntime:   at android.os.AsyncTask.finish(AsyncTask.java:631)
E/AndroidRuntime:   at android.os.AsyncTask.access$600(AsyncTask.java:177)
E/AndroidRuntime:   at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
E/AndroidRuntime:   at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime:   at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime:   at android.app.ActivityThread.main(ActivityThread.java:4960)
E/AndroidRuntime:   at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime:   at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime:   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
E/AndroidRuntime:   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
E/AndroidRuntime:   at dalvik.system.NativeStart.main(Native Method)

我的课程用于:

public class TakeCameraFragment extends Fragment {
    Camera mCamera = null;
    private CameraPreview mCameraPreview;

    protected static final int MEDIA_TYPE_IMAGE = 0;
    static String FilePAth = "";
    Button takePicture;
    static String base64string = "";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        final View rootView = inflater.inflate(R.layout.camerafragment,
                container, false);

        mCamera = getCameraInstance();

        Log.v("log_tag", "mCamera :: " + mCamera);

        mCameraPreview = new CameraPreview(getActivity(), mCamera);
        FrameLayout preview = (FrameLayout) rootView
                .findViewById(R.id.camera_preview_fragment);

        preview.addView(mCameraPreview);

        takePicture = (Button) rootView
                .findViewById(R.id.btnTakePicturefragment);
        takePicture.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                mCamera.takePicture(null, null, mPictureframent);

            }
        });

        return rootView;

    }

    public boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        releaseCamera();
    }

    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.release(); // release the camera for other applications
            mCamera = null;
        }
    }

    private Camera getCameraInstance() {

        try {
            Log.v("log_tag", "camera try:::" + mCamera);
            mCamera = Camera.open();

        } catch (Exception e) {
            // cannot get camera or does not exist
            Log.v("log_tag", "camera catch:::" + mCamera);
            releaseCamera();
        }
        return mCamera;
    }

    private static File getOutputMediaFile() {
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "MyCameraAppFragment");

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());

        FilePAth = mediaStorageDir.getPath() + File.separator + "IMG_fragment_"
                + timeStamp + ".jpg";

        Log.v("log", " FilePAth " + FilePAth);

        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_fragment_" + timeStamp + ".jpg");

        return mediaFile;
    }

    PictureCallback mPictureframent = new PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            File pictureFile = getOutputMediaFile();
            if (pictureFile == null) {
                return;
            }
            try {

                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(data);
                fos.close();


                FragmentManager fm = getFragmentManager();

                FragmentTransaction fragmentTransaction = fm.beginTransaction();
                SetPictureImageFragment fm2 = new SetPictureImageFragment();
                fragmentTransaction.replace(R.id.relative_camerafragment_id,
                        fm2, "HELLO");
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                Bundle bundle = new Bundle();
                bundle.putByteArray("position", data);
                fm2.setArguments(bundle);
                mCamera.startPreview();

            } catch (FileNotFoundException e) {

            } catch (IOException e) {
            }
        }
    };

}

使用的第二个片段:

public class SetPictureImageFragment extends Fragment {

    ImageView img;
    Bundle bundle;
    byte[] path;
    byte[] byteArrayimage;
    Button conform;
    float x;
    Bitmap b;


    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        View view = inflater.inflate(R.layout.capturepicturefragment, null);

        Log.v("log_tag","SetPictureImageFragment");
        bundle = this.getArguments();
        path = bundle.getByteArray("position");

        Log.v("log_tag","SetPictureImageFragment ::: Path :: "+path);
        img = (ImageView) view.findViewById(R.id.camera_preview_fragment_imageview);
        conform=(Button)view.findViewById(R.id.conform);




        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPurgeable = true; // inPurgeable is used to free up
                                    // memory while required


        Bitmap b = BitmapFactory.decodeByteArray(path, 0,path.length,options);

        int width = b.getWidth();
        int height = b.getHeight();
        int newWidth = 500;
        int newHeight  = 500;
         float scaleWidth = ((float) newWidth) / width;

         float scaleHeight = ((float) newHeight) / height;

         Matrix matrix = new Matrix();

         matrix.postScale(scaleWidth, scaleHeight);

         int rotation = getActivity().getWindowManager().getDefaultDisplay().getRotation();

         int finalDegree = 0;

            if(rotation == 0) {

                    finalDegree = 90;

            }

            if(rotation == 1) {

                    finalDegree = 270;

            }

            if(rotation == 2) {



                    finalDegree = 180;

            }

            if(rotation == 3) {



                    finalDegree = 90;

            }

         matrix.postRotate(finalDegree);

         Bitmap resizedBitmap = Bitmap.createBitmap(b, 0, 0,width, height, matrix, true);
         ByteArrayOutputStream stream = new ByteArrayOutputStream();
         resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
         byteArrayimage = stream.toByteArray();

         img.setScaleType(ScaleType.CENTER);
         img.setImageBitmap(resizedBitmap);


        conform.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                FragmentManager fm = getChildFragmentManager();
                FragmentTransaction fragmentTransaction = fm.beginTransaction();
                SendImageServerFragment fm2 = new SendImageServerFragment();
                // CreateStoreFragment fm2 = new CreateStoreFragment();
                fragmentTransaction.replace(R.id.relative_cameraimageview_fragment, fm2,
                        "HELLO");
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                Bundle bundle = new Bundle();
                bundle.putByteArray("position", byteArrayimage);
                fm2.setArguments(bundle);

            }
        });


        return view;
    }

}

使用的第三个片段:::

public class SendImageServerFragment extends Fragment {
    SegmentedRadioGroup segmentText;
    SegmentedRadioGroupMale segmentTextMale;
    Button sendImg;
    EditText edt_txt;
    MyApplication app;
    View view;
    Bundle bundle;
    byte[] path;
    String base64string = "";
    Bitmap b;
    String cat_id = "";
    String gender = "";
    private ProgressDialog progress;
    InputMethodManager mgr;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        view = inflater.inflate(R.layout.sendimageserver, null);

        // view.setFocusableInTouchMode(true);
        // view.requestFocus();
        bundle = this.getArguments();
        path = bundle.getByteArray("position");
        segmentText = (SegmentedRadioGroup) view
                .findViewById(R.id.segment_text);
        segmentTextMale = (SegmentedRadioGroupMale) view
                .findViewById(R.id.segment_text_male);
        sendImg = (Button) view.findViewById(R.id.btn_send_image);
        edt_txt = (EditText) view.findViewById(R.id.edt_text_store_name);

        edt_txt.requestFocus();
        mgr = (InputMethodManager) getActivity().getSystemService(
                Context.INPUT_METHOD_SERVICE);
        mgr.showSoftInput(edt_txt, InputMethodManager.SHOW_IMPLICIT);
        app = (MyApplication) getActivity().getApplicationContext();

        sendImg.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                int segTxt = segmentText.getCheckedRadioButtonId();
                RadioButton radiocatButton = (RadioButton) view
                        .findViewById(segTxt);
                int segmentTextMaleTxt = segmentTextMale
                        .getCheckedRadioButtonId();
                RadioButton radioSexButton = (RadioButton) view
                        .findViewById(segmentTextMaleTxt);

                // b = BitmapFactory.decodeByteArray(path, 0, path.length);
                base64string = Base64.encodeToString(path, Base64.DEFAULT);

                if (radiocatButton.getText().toString().equals("S")) {
                    cat_id = "4";

                } else if (radiocatButton.getText().toString().equals("C")) {
                    cat_id = "1";
                } else if (radiocatButton.getText().toString().equals("A")) {
                    cat_id = "5";
                }

                if (radioSexButton.getText().toString().equals("M")) {
                    gender = "Male";

                } else if (radioSexButton.getText().toString().equals("F")) {
                    gender = "Female";
                }

                progress = new ProgressDialog(getActivity());
                progress.setMessage("Loading...");
                new SendImageServerTask(progress).execute("Home");

            }
        });

        return view;
    }





    public class SendImageServerTask extends AsyncTask<String, Void, String> {

        public SendImageServerTask(ProgressDialog progress) {
            progress = progress;
        }

        public void onPreExecute() {
            progress.show();

        }

        @Override
        protected String doInBackground(String... arg) {

            String msg = DBAdpter.userUpdateImageStore(app.getStoreId(),
                    edt_txt.getText().toString(), cat_id, base64string, gender);
            Log.v("log_tag", " Msg " + msg);
            return msg;
        }

        @Override
        protected void onPostExecute(String result) {
            // Create here your JSONObject...

            progress.dismiss();
            Toast.makeText(getActivity().getApplicationContext(), result,
                    Toast.LENGTH_LONG).show();

            FragmentManager fm = getActivity().getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fm.beginTransaction();
            StoreProfileGridFragment fm2 = new StoreProfileGridFragment();
            fragmentTransaction.replace(R.id.relative_sendimage_send, fm2,
                    "HELLO");
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();
            hideKeybord(edt_txt);


        }

    }

    public void hideKeybord(View view) {
        mgr.hideSoftInputFromWindow(view.getWindowToken(),
                InputMethodManager.RESULT_UNCHANGED_SHOWN);
    }

}

问题答案:

这被称为 状态丢失
。您碰巧从AsyncTask提交FragmentTransaction。框架本身禁止这样做。

如果您可以接受状态丢失和用户意外行为的可能,则可以使用

FragmentTransaction#commitAllowingStateLoss()

代替

FragmentTransaction#commit()

无论如何,请考虑阅读我提供的链接,这是一种非常普遍的情况。

编辑: 此外,有您的问题的解决方法。但是我猜想,这种后果还可能导致状态丢失。尽管如此:

Handler在您的中声明一个Fragment

private Handler handler = new Handler();

然后,在您onPostExecute(..)执行以下操作:

@Override
protected void onPostExecute(String result) {    
    progress.dismiss();
    Toast.makeText(getActivity().getApplicationContext(), result,
                Toast.LENGTH_LONG).show();

    handler.post(new Runnable() {
        @Override
        public void run() {
            hideKeybord(edt_txt);
            FragmentManager fm = getActivity().getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fm.beginTransaction();
            StoreProfileGridFragment fm2 = new StoreProfileGridFragment();
            fragmentTransaction.replace(R.id.relative_sendimage_send, fm2,
                "HELLO");
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();            
        }
    });

    return;
}


 类似资料:
  • 问题内容: Android中的异步回调 试图在Android上以可靠的方式执行异步操作是不必要的麻烦,即AsyncTask确实在概念上存在缺陷吗?还是我只是缺少一些东西? 现在,一切都在引入片段之前。随着Fragments的引入,onRetainNonConfigurationInstance()已被弃用。因此,最新的Google宽容黑客手段是使用永久性的非UI片段,该片段会在配置发生变化(例如,

  • 问题内容: 在实现一个用户可以登录的应用程序时,我会遇到以下情况:如果用户已登录,请执行该操作,否则启动结果的登录活动,如果结果为Activity.RESULT_OK,请执行该操作。 我的问题是,执行perfom的操作是显示DialogFragment,但是调用 在onActivityResult回调中引发异常: 那么我该如何解决呢?我正在考虑在此处举一个标志并在onResume中显示对话框,但我

  • null java.lang.IllegalStateException:在onSaveInstanceState e/androidRuntime(9008):at android.support.v4.app.fragmentManagerImpl.checkStateLoss(fragmentManager.java:1354)e/androidRuntime(9008):at androi

  • 我有一个执行一些网络操作的自定义视图。视图根据该操作结果构建UI。 该视图包含通过Internet获取的卡的列表。此视图用于多个地方。假设其中一个是我的碎片。 下面是我在Fragment中的操作: 我的自定义视图如下所示: 好了,现在当用户从我的应用程序切换到另一个应用程序时,我的碎片可能会被销毁。我想保存我的自定义视图的状态。因此,我的观点不需要再从互联网上获取信息。因此,我在中附加了以下数据(

  • 问题内容: 我从市场上的应用程序中获取用户报告,但出现以下异常: 显然,它与FragmentManager有关,我不使用。stacktrace不显示我自己的任何类,因此我不知道发生此异常的位置以及如何防止它。 作为记录:我有一个tabhost,在每个选项卡中都有一个ActivityGroup在Activity之间切换。 问题答案: 基本上我只需要: 不要在方法上进行调用。这太糟了… 这是支持包中的