如何在 SharedPreferences 中传递 EditText 值

How to pass EditText value in SharedPreferences

MainActivity.java

EditText t=(EditText)findViewById(R.id.editText); 
String str=t.getText().toString(); 
this.getSharedPreferences("mp", 
     Context.MODE_PRIVATE).edit().putString("pt",str).apply();

Receiver.java

    TextView t= (TextView) findViewById(R.id.tv); 
    String s = this.getSharedPreferences("mp", Context.MODE_PRIVATE).getString("pt","");
    t.setText(s);

在这种情况下,当我直接传递字符串值而不是 EditText 数据时,效果很好。 哪里错了请指正。 提前致谢

您在 onCreate 函数中调用了这些函数。你应该把主题放在按钮的监听器中

button.setOnClickListener(new View.OnClickListener {
    @Override
    private void onClick(View view){
        // get text from EditText
        // put text to SharedPreferences
    }
});

当应用程序启动时,您的 EditText 中没有任何内容。