[英]DropwizardMetricServices doesn't submit the gauge metric to JMX for second time (after removing the first time)
[英]My data saves after I leave the app the first time, but after the second time, it doesn't save
我正在 android studio 上创建一个应用程序,即使他们关闭应用程序,我也想将用户输入存储到 textview 中。 我使用 SharedPreferences 来存储、加载和更新数据,但在我第二次关闭应用程序后,它不会保存我存储的数据,而是显示:{}。
有没有办法解决这个问题?
我的代码:
private String getUserName;
listTitle = (TextView)findViewById(R.id.listTitle);
listTitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View view = getLayoutInflater().inflate(R.layout.input_name_edittext, null);
EditText name = (EditText)view.findViewById(R.id.name);
builder.setView(view)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onClick(DialogInterface dialog, int which) {
String nameInputted = name.getText().toString();
if(nameInputted.chars().filter(ch -> ch != ' ').count() <= 15){
saveName(nameInputted);
listTitle.setText(nameInputted);
}
else{
Toast.makeText(MainActivity.this,
"Name is too long",
Toast.LENGTH_LONG).show();
}
}
});
builder.show();
}
loadName();
updateName();
方法:
public void saveName(String name) {
SharedPreferences sharedPreferences = getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(HASHMAP_KEY, name);
editor.apply();
}
public void loadName() {
SharedPreferences sharedPreferences = getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
getUserName = sharedPreferences.getString(HASHMAP_KEY, "Name");
}
public void updateName() {
listTitle.setText(getUserName);
}
这是使用共享首选项在 Kotlin 中执行此操作的方法
//get and set cache
fun setCache(key: String, value: String) {
val pref = context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE)
val editor = pref.edit()
editor.putString(key, value)
editor.apply()
}
fun getCache(key: String): String {
val pref = context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE)
val defaultValue = "0"
return pref.getString(key, defaultValue).toString()
}
然后你可以将它们用作
val textView = findViewById<TextView>(R.id.someTextView)
val someBtn = findViewById<Button>(R.id.someButton)
//save data from text view
someBtn.setOnClickListner{
setCache("oldData", textView.text.toString())
}
//set data to text view
if (getCache("oldData").toInt() != 0) {
//means there is some old data already, so use it
textView.text = getCache("oldData")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.