如何在onSaveInstanceState中一次保存所有布尔值?

时间:2013-11-05 11:22:46

标签: android

在调用onSaveInstanceState时,有没有办法“捕获应用程序的快照”?

否则我必须保存每个布尔值并跟踪它们并尽量不要忘记某些内容,如下所示:

@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (userAvatar != null) {
            outState.putString("userAvatar", userAvatar.toString());
            avatarAlreadyProvided = true;
        }
        if (sexIsOK) {
            outState.putBoolean("sexIsOK", true);
        }
        if (passwordIsOk) {
            outState.putBoolean("passwordIsOk", true);          
        }
        if (passwordAgainIsOk) {
            outState.putBoolean("passwordAgainIsOk", true);         
        }
        if (passwordsMatch) {
            outState.putBoolean("passwordsMatch", true);                
        }
        if (userHasProvidedOwnPhoto != false) {
            outState.putBoolean("userHasProvidedOwnPhoto", true);
            outState.putBoolean("avatarAlreadyProvided", true);
        }
        if (mImageBitmap != null) {
            outState.putParcelable("mImageBitmap", mImageBitmap);
            avatarAlreadyProvided = true;
        }
        if (usernameIsOk) {
            outState.putBoolean("usernameIsOk", true);          
        }
        if (allSignupFieldsProperlyFilled) {
            outState.putBoolean("allSignupFieldsProperlyFilled", true);         
        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle outState) {
        super.onRestoreInstanceState(outState);
        userHasProvidedOwnPhoto = outState.getBoolean("userHasProvidedOwnPhoto");
        avatarAlreadyProvided = outState.getBoolean("avatarAlreadyProvided");
        mImageBitmap = outState.getParcelable("mImageBitmap");
        userAvatar = outState.getString("userAvatar");
        iUserAvatar.setImageBitmap(mImageBitmap);
        allSignupFieldsProperlyFilled = outState.getBoolean("allSignupFieldsProperlyFilled");
        usernameIsOk = outState.getBoolean("usernameIsOk");
        passwordsMatch = outState.getBoolean("passwordsMatch");
        passwordAgainIsOk = outState.getBoolean("passwordAgainIsOk");
        passwordIsOk = outState.getBoolean("passwordIsOk");
        sexIsOK = outState.getBoolean("sexIsOK");


    }

我总是忘记一些事情而且我搞砸了。必须有其他方式......

1 个答案:

答案 0 :(得分:2)

将变量包装到Java类中并使用序列化。您可以使用Gson进行Json序列化。

How do I serialize an object and save it to a file in Android?