请问如何使用onSaveInstanceState示例

时间:2011-06-29 18:51:15

标签: android savestate

归结为拯救一个州,我很困惑。所以我知道当活动即将被销毁时会调用onSaveInstanceState(Bundle)。但是,如何将信息存储在其中并将其恢复到onCreate(Bundle savedInstanceState)中的原始状态?我不明白这个捆绑包将如何恢复信息。如果有人可以提供一个例子,那将会很有帮助。 开发指南没有很好地解释这一点。

public class Conversation extends Activity {
    private ProgressDialog progDialog;
    int typeBar;
    TextView text1;
    EditText edit;
    Button respond;
    private String name;
    private String textAtView;
    private String savedName;

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        setContentView(R.layout.dorothydialog);
        text1 = (TextView)findViewById(R.id.dialog);
        edit = (EditText)findViewById(R.id.repsond);
        respond = (Button)findViewById(R.id.button01);

        if(savedInstanceState != null){
            savedInstanceState.get(savedName);
            text1.setText(savedName);
        }
        else{
            text1.setText("Hello! What is your name?");
            respond.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    name = edit.getText().toString();
                    text1.setText("Nice to meet you "+ name);
                }   
            });
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState){
        super.onSaveInstanceState(outState);
        outState.putString(savedName, name);
    }
}

7 个答案:

答案 0 :(得分:177)

Bundle是您要保存的所有信息的容器。您可以使用put *函数将数据插入其中。以下是可用于在Bundle中存储数据的put函数的简短列表(还有更多)。

putString
putBoolean
putByte
putChar
putFloat
putLong
putShort
putParcelable (used for objects but they must implement Parcelable)

在您的onCreate函数中,此Bundle将被传回程序。检查应用程序是否正在重新加载或首次启动的最佳方法是:

if (savedInstanceState != null) {
    // Then the application is being reloaded
}

要恢复数据,请使用get *函数,就像put *函数一样。数据存储为名称 - 值对。这就像一个hashmap。你提供了一个键和值,然后当你想要返回值时,你给出键,函数得到值。这是一个简短的例子。

@Override
public void onSaveInstanceState(Bundle outState) {
   outState.putString("message", "This is my message to be reloaded");
   super.onSaveInstanceState(outState);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        String message = savedInstanceState.getString("message");
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }
}

您保存的信息将被烘烤到屏幕上。希望这会有所帮助。

答案 1 :(得分:31)

所有新Android开发人员应该知道的一个主要注意事项是,只要您为其分配ID,Widgets(TextView,Buttons等)中的任何信息都将由Android自动保留。这意味着大多数UI状态都会得到解决而没有问题。只有当您需要存储其他数据时才会出现问题。

来自Android Docs

  

你需要的唯一工作就是   提供一个唯一的ID(与...   每个小部件的android:id属性)   你想保存它的状态。如果一个   widget没有ID,那么它   无法保存其状态

答案 2 :(得分:5)

一个很好的信息:你不需要在onCreate()方法中检查Bundle对象是否为null。使用onRestoreInstanceState()方法,系统在onStart()方法之后调用该方法。仅当存在要恢复的已保存状态时,系统才会调用onRestoreInstanceState(),因此您无需检查Bundle是否为空

答案 3 :(得分:3)

商店信息:

static final String PLAYER_SCORE = "playerScore";
static final String PLAYER_LEVEL = "playerLevel";

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(PLAYER_SCORE, mCurrentScore);
    savedInstanceState.putInt(PLAYER_LEVEL, mCurrentLevel);

// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}

如果您不想在onCreate-Method中恢复信息:

以下是示例:Recreating an Activity

  

您可以选择实现onRestoreInstanceState(),系统在onStart()方法之后调用,而不是在onCreate()期间恢复状态。仅当存在要恢复的已保存状态时,系统才会调用onRestoreInstanceState(),因此您无需检查Bundle是否为空

public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);

// Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(PLAYER_SCORE);
mCurrentLevel = savedInstanceState.getInt(PLAYER_LEVEL);
}

答案 4 :(得分:0)

基本上onSaveInstanceState(Bundle outBundle)会给你一个包。 当您查看Bundle类时,您会发现可以在其中放入许多不同的东西。在下一次调用onCreate()时,你只需将Bundle作为参数返回。 然后,您可以再次阅读您的值并恢复您的活动。

假设您有一个EditText活动。用户在其中写了一些文字。 之后系统调用你的onSaveInstanceState()。 您从EditText读取文本并通过Bundle.putString(“edit_text_value”,theValue)将其写入Bundle。

现在调用onCreate。您检查提供的包是否为空。如果是这样的话, 你可以通过Bundle.getString(“edit_text_value”)恢复你的价值,然后把它放回你的EditText。

答案 5 :(得分:0)

这是额外的信息。

想象一下这个场景

  1. ActivityA启动ActivityB。
  2. ActivityB按

    启动新的ActivityAPrime
    Intent intent = new Intent(getApplicationContext(), ActivityA.class);
    startActivity(intent);
    
  3. ActivityAPrime与ActivityA没有任何关系 在这种情况下,ActivityAPrime.onCreate()中的Bundle将为null。

  4. 如果ActivityA和ActivityAPrime应该是相同的活动而不是不同的活动, ActivityB应该调用finish()而不是使用startActivity()。

答案 6 :(得分:0)

如果未从savedInstanceState加载数据,请使用以下代码  问题是url调用是不是完全完成所以,检查数据是否已加载然后显示instanceState值。

//suppose data is not Loaded to savedInstanceState at 1st swipe
if (savedInstanceState == null && !mAlreadyLoaded){
    mAlreadyLoaded = true;
    GetStoryData();//Url Call
} else {
    if (listArray != null) {  //Data Array From JsonArray(ListArray)
        System.out.println("LocalData  " + listArray);
        view.findViewById(R.id.progressBar).setVisibility(View.GONE);
    }else{
        GetStoryData();//Url Call
    }
}