使用savedInstanceState保存数据

时间:2017-10-12 08:18:11

标签: java android save savestate

MainActivity.java

 package com.jamesvuong.footballscorekeeper;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    final int TOUCHDOWN_POINTS = 6;
    final int FIELD_GOAL_POINTS = 3;
    final int EXTRA_POINT_1_POINT = 1;
    final int EXTRA_POINT_2_POINTS = 2;
    final int SAFETY_POINTS = 2;
    String score_a , score_b;
    String TEXT_A , TEXT_B;
    int team_a_score;
    int team_b_score;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); // Always call the superclass first


        // Check whether we're recreating a previously destroyed instance
        if (savedInstanceState != null) {
            // Restore value of members from saved state
            team_a_score = savedInstanceState.getInt(TEXT_A);
            team_b_score = savedInstanceState.getInt(TEXT_B);
        }
        else {
            // Probably initialize members with default values for a new instance
            team_a_score = 0;
            team_b_score = 0;
        }
        setContentView(R.layout.activity_main);
        displayTeamAScore(team_a_score);
        displayTeamBScore(team_b_score);

    }



    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save the user's current game state
        savedInstanceState.putInt(TEXT_A,team_a_score);
        savedInstanceState.putInt(TEXT_B, team_b_score);


        // Always call the superclass so it can save the view hierarchy state
        super.onSaveInstanceState(savedInstanceState);
    }
    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
        team_a_score = savedInstanceState.getInt(TEXT_A);
        team_b_score = savedInstanceState.getInt(TEXT_B);
    }


    /**
     * Update Scores
     */
    public void resetScores(View v) {
        team_a_score = 0;
        team_b_score = 0;
        displayTeamAScore(team_a_score);
        displayTeamBScore(team_b_score);
    }

    public void updateTeamScore(View v) {
        switch(v.getId()) {
            case R.id.team_a_touchdown:
                team_a_score += TOUCHDOWN_POINTS;
                break;
            case R.id.team_a_field_goal:
                team_a_score += FIELD_GOAL_POINTS;
                break;
            case R.id.team_a_extra_point_1:
                team_a_score += EXTRA_POINT_1_POINT;
                break;
            case R.id.team_a_extra_point_2:
                team_a_score += EXTRA_POINT_2_POINTS;
                break;
            case R.id.team_a_safety:
                team_a_score += SAFETY_POINTS;
                break;

            case R.id.team_b_touchdown:
                team_b_score += TOUCHDOWN_POINTS;
                break;
            case R.id.team_b_field_goal:
                team_b_score += FIELD_GOAL_POINTS;
                break;
            case R.id.team_b_extra_point_1:
                team_b_score += EXTRA_POINT_1_POINT;
                break;
            case R.id.team_b_extra_point_2:
                team_b_score += EXTRA_POINT_2_POINTS;
                break;
            case R.id.team_b_safety:
                team_b_score += SAFETY_POINTS;
                break;

            default:
                break;
        }

        displayTeamAScore(team_a_score);
        displayTeamBScore(team_b_score);
    }

    /**
     * Display Scores
     */
    public void displayTeamAScore(int score) {
        TextView scoreView = (TextView) findViewById(R.id.team_a_score);
        scoreView.setText(String.valueOf(score));
    }

    public void displayTeamBScore(int score) {
        TextView scoreView = (TextView) findViewById(R.id.team_b_score);
        scoreView.setText(String.valueOf(score));
    }

}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context="com.jamesvuong.footballscorekeeper.MainActivity">


    <LinearLayout
        android:id="@+id/score_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:layout_marginBottom="10dp"
        android:orientation="horizontal">

        <LinearLayout
            android:id="@+id/team_a_score_container"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="6"
            android:orientation="vertical">

            <TextView
                android:id="@+id/team_a_label"
                android:text="Team A"
                style="@style/TeamLabelStyle"/>

            <TextView
                android:id="@+id/team_a_score"
                android:text="0"
                android:saveEnabled="true"
                style="@style/ScoreTextStyle"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="-"
                android:gravity="center"
                android:textStyle="bold"
                android:textSize="30sp"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/team_b_score_container"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="6"
            android:orientation="vertical">

            <TextView
                android:id="@+id/team_b_label"
                android:text="Team B"
                style="@style/TeamLabelStyle"/>

            <TextView
                android:id="@+id/team_b_score"
                android:text="0"
                android:saveEnabled="true"
                style="@style/ScoreTextStyle"/>

        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@android:color/darker_gray"
        android:layout_marginBottom="10dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/scoring_buttons_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="4"
        android:layout_gravity="center"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/touchdown_container"
            style="@style/ScoreTypeButtonContainerStyle">

            <Button
                android:id="@+id/team_a_touchdown"
                style="@style/ScoreButtonStyle"
                android:text="+6"
                android:onClick="updateTeamScore"/>

            <TextView
                android:text="Touchdown"
                style="@style/ScoreTypeLabelStyle"/>

            <Button
                android:id="@+id/team_b_touchdown"
                style="@style/ScoreButtonStyle"
                android:text="+6"
                android:onClick="updateTeamScore"/>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/field_goal_container"
            style="@style/ScoreTypeButtonContainerStyle">

            <Button
                android:id="@+id/team_a_field_goal"
                style="@style/ScoreButtonStyle"
                android:text="+3"
                android:onClick="updateTeamScore"/>

            <TextView
                android:text="Field Goal"
                style="@style/ScoreTypeLabelStyle"/>

            <Button
                android:id="@+id/team_b_field_goal"
                style="@style/ScoreButtonStyle"
                android:text="+3"
                android:onClick="updateTeamScore"/>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/extra_point_container"
            style="@style/ScoreTypeButtonContainerStyle">

            <Button
                android:id="@+id/team_a_extra_point_1"
                style="@style/ScoreButtonStyle"
                android:text="+1"
                android:onClick="updateTeamScore"/>

            <Button
                android:id="@+id/team_a_extra_point_2"
                style="@style/ScoreButtonStyle"
                android:text="+2"
                android:onClick="updateTeamScore"/>

            <TextView
                style="@style/ScoreTypeLabelStyle"
                android:text="Extra Point" />

            <Button
                android:id="@+id/team_b_extra_point_1"
                style="@style/ScoreButtonStyle"
                android:text="+1"
                android:onClick="updateTeamScore"/>

            <Button
                android:id="@+id/team_b_extra_point_2"
                style="@style/ScoreButtonStyle"
                android:text="+2"
                android:onClick="updateTeamScore"/>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/safety_container"
            style="@style/ScoreTypeButtonContainerStyle">

            <Button
                android:id="@+id/team_a_safety"
                style="@style/ScoreButtonStyle"
                android:text="+2"
                android:onClick="updateTeamScore"/>

            <TextView
                style="@style/ScoreTypeLabelStyle"
                android:text="Safety"/>

            <Button
                android:id="@+id/team_b_safety"
                style="@style/ScoreButtonStyle"
                android:text="+2"
                android:onClick="updateTeamScore"/>

        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@android:color/darker_gray"
        android:layout_marginBottom="10dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#333333"
            android:onClick="resetScores"
            android:text="Reset"
            android:textColor="#FFFFFF" />

    </LinearLayout>
</LinearLayout>

我想保存一些值,比如团队的得分,这样即使在应用程序被杀死(不在后台运行)之后,分数也会保存,并且可以在用户再次打开app时保留。尝试使用&#39; savedInstanceState&#39;但它不起作用。请帮忙。我是android开发的初学者。

2 个答案:

答案 0 :(得分:0)

savedInstanceState用于在屏幕旋转期间保存应用的当前状态,而不是永久保存数据。 SharedPreferences正是您要找的。这是一个例子:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

// save
sharedPreferences.edit()
        .putString("key1", "value")
        .putInt("key2", 10)
        .apply();

// retrieve
String stringValue = sharedPreferences.getString("key1", null);
int intValue = sharedPreferences.getInt("key2", -1);

// null and -1 are default values if not found

答案 1 :(得分:0)

如果您的应用尚未被杀死,那么您可以使用saveInstanceState / Application类存储值,否则U必须使用共享首选项或Sqlite /其他ORM。