请教如何使用onSavedInstanceState示例

发布于 2024-11-18 06:37:03 字数 1485 浏览 3 评论 0原文

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

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);
    }
}

I'm confused when it comes down to saving a state. So I know that onSaveInstanceState(Bundle) is called when the activity is about to be destroyed. But how do you store your information in it and bring it back to its original state in onCreate(Bundle savedInstanceState)? I don't understand how this bundle will restore information. It would be helpful if someone can provide an example.
The Dev guide doesn't do a good job of explaining this.

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);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

我乃一代侩神 2024-11-25 06:37:03

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
}

要取回数据,请像 put* 函数一样使用 get* 函数。数据存储为名称-值对。这就像一个哈希图。您提供一个键和值,然后当您想要返回值时,您给出键,函数就会获取值。这是一个简短的例子。

@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();
    }
}

您保存的消息将显示在屏幕上。

The Bundle is a container for all the information you want to save. You use the put* functions to insert data into it. Here's a short list (there are more) of put functions you can use to store data in the Bundle.

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

In your onCreate function, this Bundle is handed back to the program. The best way to check if the application is being reloaded, or started for the first time is:

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

To get the data back out, use the get* functions just like the put* functions. The data is stored as a name-value pair. This is like a hashmap. You provide a key and the value, then when you want the value back, you give the key and the function gets the value. Here's a short example.

@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();
    }
}

Your saved message will be toasted to the screen.

巨坚强 2024-11-25 06:37:03

所有新的 Android 开发人员都应该知道的一个重要注意事项是,只要您为 Widget(TextView、Buttons 等)分配一个 ID,Android 就会自动保留它们中的任何信息。因此,这意味着大部分 UI 状态都已得到处理,不会出现任何问题。只有当您需要存储其他数据时,这才会成为问题。

来自 Android 文档

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

One major note that all new Android developers should know is that any information in Widgets (TextView, Buttons, etc.) will be persisted automatically by Android as long as you assign an ID to them. So that means most of the UI state is taken care of without issue. Only when you need to store other data does this become an issue.

From Android Docs:

The only work required by you is to
provide a unique ID (with the
android:id attribute) for each widget
you want to save its state. If a
widget does not have an ID, then it
cannot save its state

苯莒 2024-11-25 06:37:03

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

A good information: you don't need to check whether the Bundle object is null into the onCreate() method. Use the onRestoreInstanceState() method, which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null

冷夜 2024-11-25 06:37:03

存储信息:

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 中恢复信息:

以下是示例:重新创建活动

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

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);
}

Store information:

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);
}

If you don't want to restore information in your onCreate-Method:

Here are the examples: Recreating an Activity

Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null

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);
}
就此别过 2024-11-25 06:37:03

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

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

现在 onCreate 被调用。您检查提供的包是否不为空。如果是这样的话,
您可以通过 Bundle.getString("edit_text_value") 恢复您的值并将其放回您的 EditText 中。

Basically onSaveInstanceState(Bundle outBundle) will give you a bundle.
When you look at the Bundle class, you will see that you can put lots of different stuff inside it. At the next call of onCreate(), you just get that Bundle back as an argument.
Then you can read your values again and restore your activity.

Lets say you have an activity with an EditText. The user wrote some text inside it.
After that the system calls your onSaveInstanceState().
You read the text from the EditText and write it into the Bundle via Bundle.putString("edit_text_value", theValue).

Now onCreate is called. You check if the supplied bundle is not null. If thats the case,
you can restore your value via Bundle.getString("edit_text_value") and put it back into your EditText.

提赋 2024-11-25 06:37:03

这是为了提供额外信息。

想象一下这样的场景:

  1. ActivityA 启动 ActivityB。
  2. ActivityB 推出新的 ActivityAPrime

    Intent Intent = new Intent(getApplicationContext(), ActivityA.class);
    启动活动(意图);
    
  3. ActivityB通过

    ActivityAPrime与ActivityA没有关系 。
    在这种情况下,ActivityAPrime.onCreate() 中的 Bundle 将为 null。

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

This is for extra information.

Imagine this scenario

  1. ActivityA launch ActivityB.
  2. ActivityB launch a new ActivityAPrime by

    Intent intent = new Intent(getApplicationContext(), ActivityA.class);
    startActivity(intent);
    
  3. ActivityAPrime has no relationship with ActivityA.
    In this case the Bundle in ActivityAPrime.onCreate() will be null.

If ActivityA and ActivityAPrime should be the same activity instead of different activities,
ActivityB should call finish() than using startActivity().

拒绝两难 2024-11-25 06:37:03

如果数据未从 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
    }
}

If Data Is not Loaded From savedInstanceState use following code.
The problem is url call is not to complete fully so, check if data is loaded then to show the instanceState value.

//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
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文