因此,当我单击“保存”按钮时,我想存储比赛得分,包括球队名称和日期,这些得分是从篮球比赛计数器应用程序中存储的。我是编程新手,我搜索的所有内容都帮不了我。

这是Java代码:

包com.example.android.courtcounter;

导入android.support.v7.app.AppCompatActivity;

导入android.os.Bundle;

导入android.view.View;

导入android.widget.TextView;

导入android.widget.Toast;

公共类MainActivity扩展了AppCompatActivity {

int scoreTeamA = 0;
int scoreTeamB = 0;

@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); displayForTeamA(0); displayForTeamB(0); setTitle("Basketball Count"); Toast.makeText(getApplicationContext(), "You can change team names and scores manually by clicking on them", Toast.LENGTH_LONG).show();}// +3 Points for Team Apublic void addThreeForTeamA (View view) { scoreTeamA = scoreTeamA + 3; displayForTeamA(scoreTeamA);}// +2 Points for Team Apublic void addTwoForTeamA (View view) { scoreTeamA = scoreTeamA + 2; displayForTeamA(scoreTeamA);}// +1 Point for Team Apublic void addOneForTeamA (View view) { scoreTeamA = scoreTeamA +1; displayForTeamA(scoreTeamA);}// Displays the given score for Team A.public void displayForTeamA(int score) { TextView scoreView = (TextView) findViewById(R.id.team_a_score); scoreView.setText(String.valueOf(score));}// +3 Points for Team Bpublic void addThreeForTeamB (View view) { scoreTeamB = scoreTeamB + 3; displayForTeamB(scoreTeamB);}// +2 Points for Team Bpublic void addTwoForTeamB (View view) { scoreTeamB = scoreTeamB + 2; displayForTeamB(scoreTeamB);}// +1 Point for Team Bpublic void addOneForTeamB (View view) { scoreTeamB = scoreTeamB +1; displayForTeamB(scoreTeamB);}// Displays the given score for Team B.public void displayForTeamB(int score) { TextView scoreView = (TextView) findViewById(R.id.team_b_score); scoreView.setText(String.valueOf(score));}public void resetScore (View view) { scoreTeamA = 0; scoreTeamB = 0; displayForTeamA(scoreTeamA); displayForTeamB(scoreTeamB);}

}


我已经将分数和团队名称存储在EditText视图中,并希望保存它们并在以后加载。任何人都知道如何保存和加载特定游戏分数?

谢谢

最佳答案

我从Udacity出色的“ Android入门”课程中识别了此代码。.您必须使用sharedPreferences保存分数。例如:

SharedPreferences sharedPref = getSharedPreferences(
                getString(R.string.preference_file_key), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("scoreTeamA", scoreTeamA);
editor.putInt("scoreTeamB", scoreTeamB);
editor.apply();


然后检索值:

SharedPreferences sharedPref = getSharedPreferences(
                getString(R.string.preference_file_key), Context.MODE_PRIVATE);
int scoreTeamA = sharedPref.getInt(scoreTeamA, 0);
int scoreTeamB = sharedPref.getInt(scoreTeamB, 0);

07-28 13:12