[英]How do I save variable values across Activities in Android Studio
我是新来的,对编程也很陌生。 我目前正在做一个项目,现在我已经被困了一周。我唯一想做的就是保存两个变量,以便在应用程序关闭并重新打开后仍然可以看到它。 同样由于某种原因,当我打开设置活动时,我的变量值被设置回零。
我知道其他人已经发布了类似的问题,但我无法使其适应我的工作。 我不明白我读到的很多东西,比如 SharedPreferences、onPause() 和 GAME_STATE_KEY。 任何人都可以在不链接 Android 文档文章的情况下解释如何做这样的事情吗? 我什至不明白文档所说的内容,并且在那里复制/粘贴代码似乎不起作用。
这是我的主要活动
package com.example.courtcounter;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity<format> extends AppCompatActivity {
TextView textView;
int scoreTeamA = 0;
int scoreTeamB = 0;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy\n hh:mm aa");
String format = simpleDateFormat.format(new Date());
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.team_a_score);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String shareMessage = createMessage(format, scoreTeamA, scoreTeamB);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_SUBJECT, "Match Score");
intent.setType("text/*");
intent.putExtra(Intent.EXTRA_TEXT, shareMessage);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings){
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
private String createMessage(String date, int TeamA, int TeamB){
EditText editTeamA = findViewById(R.id.team_a_name);
String teamAName =editTeamA.getText().toString();
EditText editTeamB = findViewById(R.id.team_b_name);
String teamBName = editTeamB.getText().toString();
String shareMessage =format +"\n"+ teamAName+ " : "+ TeamA + "\n" + teamBName + " : "+ TeamB;
return shareMessage;
}
/** Resets score of boths teams to 0
*/
public void resetScore(View v){
scoreTeamA = 0;
scoreTeamB = 0;
displayForTeamA(scoreTeamA);
displayForTeamB(scoreTeamB);
}
/**
* Displays the given score for Team A.
*/
public void displayForTeamA(int scoreTeamA){
TextView scoreViewA = (TextView)findViewById(R.id.team_a_score);
String teamA = scoreViewA.getText().toString();
scoreViewA.setText(String.valueOf(scoreTeamA));
}
/**
* Displays the given score for Team B.
*/
public void displayForTeamB(int score) {
TextView scoreViewB = (TextView) findViewById(R.id.team_b_score);
String teamB = scoreViewB.getText().toString();
scoreViewB.setText(String.valueOf(score));
}
/**
* This method is called when the +3 points button is clicked.
*/
public void ThreeA(View view){
scoreTeamA = scoreTeamA +3;
displayForTeamA(scoreTeamA);
}
/**
* This method is called when the +2 points button is clicked.
*/
public void TwoA(View view){
scoreTeamA = scoreTeamA +2;
displayForTeamA(scoreTeamA);
}
/**
* This method is called when the FREE THROW button is clicked.
*/
public void OneA(View view){
scoreTeamA = scoreTeamA + 1;
displayForTeamA(scoreTeamA);
}
/**
* This method is called when the +3 points button is clicked.
*/
public void ThreeB(View view){
scoreTeamB = scoreTeamB +3;
displayForTeamB(scoreTeamB);
}
/**
* This method is called when the +2 points button is clicked.
*/
public void TwoB(View view){
scoreTeamB = scoreTeamB +2;
displayForTeamB(scoreTeamB);
}
/**
* This method is called when the FREE THROW button is clicked.
*/
public void OneB(View view){
scoreTeamB = scoreTeamB + 1;
displayForTeamB(scoreTeamB);
}
}
我是否必须更改我的 SettingActivity 和 SettingsFragment 来帮助解决这个问题,还是不需要?
谢谢。
如果您希望它们在应用程序完全关闭时仍然存在, SharedPreferences
就是您要寻找的。 这是一个键/值存储,允许您存储即使在活动被销毁后仍然存在的数据。 基本上,它们有两个部分:
所以首先你得到一个参考你的共享偏好使用
SharedPreferences.Editor editor = getSharedPreferences(
MY_PREFS_NAME, MODE_PRIVATE).edit();
这个MY_PREFS_NAME
可以是你喜欢的任何字符串。 它允许您访问共享首选项的“切片”。 一旦你得到这个参考,现在你就可以开始阅读和写作了。
来写:
editor.putInt("scoreViewA", 5);
editor.putInt("scoreViewB", 12);
editor.apply();
后来阅读:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
int scoreViewA = prefs.getInt("scoreViewA", 0);
int scoreViewB = prefs.getInt("scoreViewB", 0);
getInt
中的第二个参数是默认值,如果找不到给定的键,将使用该参数。 请注意,在检索对共享首选项的引用时,您必须再次使用相同的MY_PREFS_NAME
。
最后,请注意,在写入共享首选项时,我们在写入任何更改之前调用edit()
,然后调用apply()
。
您需要将代码写入onPause
方法中的共享首选项。 只要活动不再在前台,就会触发。 然后在onResume
方法中阅读。 当应用程序在前台重新获得焦点时会触发此方法。
@Override
public void onPause() {
super.onPause();
// write to shared preferences
}
@Override
public void onResume() {
super.onResume();
// read from shared preferences
}
如果你只是想将一个变量从一个活动共享到一个新活动,你可以使用捆绑包。 查看这个答案以获得一个很好的例子。
希望对您有所帮助,欢迎来到 Stackoverflow!
我终于想通了,这很宣泄。 我的主要问题是弄清楚将方法放在哪里,看起来我不需要onPause()
和onResume()
方法。
首先在 AndroidManifest.xml 文件中,我添加了android:launchMode="singleTop"
但由于我设法保存了首选项,因此不需要它。
在我的显示方法中,我添加了SharedPreferences myScoreB = getSharedPreferences("teamBScore", Context.MODE_PRIVATE); SharedPreferences.Editor editor = myScoreB.edit();editor.putInt("scoreB", scoreTeamB);editor.commit();
SharedPreferences myScoreB = getSharedPreferences("teamBScore", Context.MODE_PRIVATE); SharedPreferences.Editor editor = myScoreB.edit();editor.putInt("scoreB", scoreTeamB);editor.commit();
读取数据部分令人困惑,但最后我设法在 oncreate 方法SharedPreferences myScoreB = this.getSharedPreferences("teamBScore", Context.MODE_PRIVATE);scoreTeamB = myScoreB.getInt("scoreB", 0);scoreViewB.setText(String.valueOf(scoreTeamB));
它现在可以处理屏幕旋转,而无需重新创建整个布局以及重新启动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.