gpt4 book ai didi

java - SharedPreferences 不保存文本值

转载 作者:行者123 更新时间:2023-12-02 08:51:46 26 4
gpt4 key购买 nike

**

我正在尝试使用 Sharedpreferences 保存文本变量。我通过这段代码保存了变量。但是当我单击按钮时,保存的变量将返回到 0。我想从保存的值开始计数。请帮助我

**int 计数器 = 0;

public static final  String SHARED_PREF="shared";
public static final String TEXT="text";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);

counterView=findViewById(R.id.counterid);
Btn=findViewById(R.id.button1);

Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

counter++;
counterView.setText(Integer.toString(counter));

SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(TEXT,counterView.getText().toString());
editor.commit();

}

});


SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String tValue = sp.getString(TEXT,"");
counterView.setText(tValue);


}

}

最佳答案

考虑到您提供的信息,我认为您需要为 counter 提供存储在 SharedPreferences 中的值,以便在按下按钮时继续计数再次。试试这个:

 int counter = 0;
Button adBtn;
TextView counterView;
public static final String SHARED_PREF="shared";
public static final String TEXT="text";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

counterView=findViewById(R.id.counterid);
adBtn=findViewById(R.id.button1);

adBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences counterSp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String correctCounterValue = counterSp.getString(TEXT,"");
counter = Integer.valueOf(correctCounterValue);
counter++;
counterView.setText(Integer.toString(counter));

SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(TEXT,counterView.getText().toString());
editor.commit();

}

});


SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String tValue = sp.getString(TEXT,"");
counterView.setText(tValue);


}

关于java - SharedPreferences 不保存文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60729651/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com