如何从共享首选项中检索编辑文本中的数据



嗨,谁能告诉我我如何得到保存后的数据编辑文本,我的意思是,当我保存一些文本,然后我想文本将出现在编辑文本所有的时间谢谢。下面是我的代码:

public class MainActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private EditText inputName;
    private TextInputLayout inputLayoutName;
    private Button btnSave;
    public static final String MyPREFERENCES = "MyPrefs" ;
    public static final String Message = "nameKey";
    SharedPreferences sharedpreferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_name);
       inputName = (EditText) findViewById(R.id.input_message);
        btnSave = (Button) findViewById(R.id.btn_save);
        inputName.addTextChangedListener(new MyTextWatcher(inputName));
        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String m  = inputName.getText().toString();
                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString(Message, m);
                editor.apply();
                Toast.makeText(getApplicationContext(), "Thank You!", Toast.LENGTH_SHORT).show();
            }
        });
    }
inputName.setText(sharedpreferences.getString(Message, "default_value"));

试试这个

  btnSave.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String m  = inputName.getText().toString();
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putString(Message, m);
                    editor.apply();
                    Toast.makeText(getApplicationContext(), "Thank You!", Toast.LENGTH_SHORT).show();
                    inputName.setText(m, TextView.BufferType.EDITABLE); //set the text here
                }
            });

最新更新