[英]How do I save variable values across Activities in Android Studio
I'm new here and also new to programming.我是新来的,对编程也很陌生。 I'm currently working on a project and I've been stuck for bout a week now.The only thing I want to do is save two variables so that it still can be seen after the app is closed and reopened.我目前正在做一个项目,现在我已经被困了一周。我唯一想做的就是保存两个变量,以便在应用程序关闭并重新打开后仍然可以看到它。 Also for some reason when I open the Settings Activity my variables values are set back to zero.同样由于某种原因,当我打开设置活动时,我的变量值被设置回零。
I'm aware that others have posted similar questions like this but I just can't adapt it to my work.我知道其他人已经发布了类似的问题,但我无法使其适应我的工作。 I don't understand a lot of things I read like SharedPreferences, onPause(), and GAME_STATE_KEY.我不明白我读到的很多东西,比如 SharedPreferences、onPause() 和 GAME_STATE_KEY。 Could anyone please explain how to do such a thing without linking the Android Documentation articles?任何人都可以在不链接 Android 文档文章的情况下解释如何做这样的事情吗? I don't even understand what the documentation says and copy/pasting code there doesn't seem to work.我什至不明白文档所说的内容,并且在那里复制/粘贴代码似乎不起作用。
This is my MainActivity这是我的主要活动
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);
}
}
Do I have to change My SettingActivity and SettingsFragment to help solve this or is it not needed?我是否必须更改我的 SettingActivity 和 SettingsFragment 来帮助解决这个问题,还是不需要?
Thanks.谢谢。
If you want them to persist when the app is completely closed, SharedPreferences
is the one you're looking for.如果您希望它们在应用程序完全关闭时仍然存在, SharedPreferences
就是您要寻找的。 This is a key/value store that allows you to store data that persists even after the activity is destroyed.这是一个键/值存储,允许您存储即使在活动被销毁后仍然存在的数据。 Basically, they have two parts:基本上,它们有两个部分:
So first you get a reference to your shared preferences using所以首先你得到一个参考你的共享偏好使用
SharedPreferences.Editor editor = getSharedPreferences(
MY_PREFS_NAME, MODE_PRIVATE).edit();
This MY_PREFS_NAME
can be any string you like.这个MY_PREFS_NAME
可以是你喜欢的任何字符串。 It allows you access your "slice" of the shared preferences.它允许您访问共享首选项的“切片”。 Once you get this reference, now you can begin reading and writing to them.一旦你得到这个参考,现在你就可以开始阅读和写作了。
To write:来写:
editor.putInt("scoreViewA", 5);
editor.putInt("scoreViewB", 12);
editor.apply();
And later to read:后来阅读:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
int scoreViewA = prefs.getInt("scoreViewA", 0);
int scoreViewB = prefs.getInt("scoreViewB", 0);
This second parameter in getInt
is a default that will be used if the given key is not found. getInt
中的第二个参数是默认值,如果找不到给定的键,将使用该参数。 Note that once again you must use the same MY_PREFS_NAME
when retrieving a reference to the shared preferences.请注意,在检索对共享首选项的引用时,您必须再次使用相同的MY_PREFS_NAME
。
Finally, note that when writing to shared preferences, we call edit()
before writing any changes, and we call apply()
afterwards.最后,请注意,在写入共享首选项时,我们在写入任何更改之前调用edit()
,然后调用apply()
。
You'll want to put your code to write to shared preferences in your onPause
method.您需要将代码写入onPause
方法中的共享首选项。 This fires whenever the activity is no longer in the foreground.只要活动不再在前台,就会触发。 Then do your reading in the onResume
method.然后在onResume
方法中阅读。 This method fires when the app regains focus in the foreground.当应用程序在前台重新获得焦点时会触发此方法。
@Override
public void onPause() {
super.onPause();
// write to shared preferences
}
@Override
public void onResume() {
super.onResume();
// read from shared preferences
}
And if you're just trying to share a variable from one activity to a new one, you can use a bundle.如果你只是想将一个变量从一个活动共享到一个新活动,你可以使用捆绑包。 Check out this answer for a good example.查看这个答案以获得一个很好的例子。
Hope that helps, welcome to Stackoverflow!希望对您有所帮助,欢迎来到 Stackoverflow!
I finally figured it out, it was very Cathartic.我终于想通了,这很宣泄。 My main issue was figuring out where to put the methods and it looks like I didn't need the onPause()
and onResume()
methods.我的主要问题是弄清楚将方法放在哪里,看起来我不需要onPause()
和onResume()
方法。
First in the AndroidManifest.xml file I added android:launchMode="singleTop"
but it the end it wasn't needed since I managed to save the preferences.首先在 AndroidManifest.xml 文件中,我添加了android:launchMode="singleTop"
但由于我设法保存了首选项,因此不需要它。
In my display methods I added 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();
SharedPreferences myScoreB = getSharedPreferences("teamBScore", Context.MODE_PRIVATE); SharedPreferences.Editor editor = myScoreB.edit();editor.putInt("scoreB", scoreTeamB);editor.commit();
The reading data part was confusing but in the end I managed to do it in the oncreate method SharedPreferences myScoreB = this.getSharedPreferences("teamBScore", Context.MODE_PRIVATE);scoreTeamB = myScoreB.getInt("scoreB", 0);scoreViewB.setText(String.valueOf(scoreTeamB));
读取数据部分令人困惑,但最后我设法在 oncreate 方法SharedPreferences myScoreB = this.getSharedPreferences("teamBScore", Context.MODE_PRIVATE);scoreTeamB = myScoreB.getInt("scoreB", 0);scoreViewB.setText(String.valueOf(scoreTeamB));
It now handle screen rotations without recreating the entire layout as well as restarts.它现在可以处理屏幕旋转,而无需重新创建整个布局以及重新启动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.