[英]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.