Save entered text in editText via button

后端 未结 2 2009
礼貌的吻别
礼貌的吻别 2020-12-17 07:57

i want to save a String\'s value that is entenred in EditText using sharedPreferences. and show text when activity starts

public cl         


        
相关标签:
2条回答
  • 2020-12-17 08:39

    Change your function:

    private void makeTag(String tag){
            String or = savednotes.getString("KEY_NAME", "0");// here, '0' is default value
            Editor preferencesEditor = savednotes.edit();
            preferencesEditor.putString("KEY_NAME",tag);
            preferencesEditor.commit();
    
        }
    

    EDIT

    onCreate()
    {
    savednotes=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
     }
    
    0 讨论(0)
  • 2020-12-17 08:41

    You have to change your code with two new lines with comments below:

    public class enteredText extends Activity{
    
        private Button savenotebutton1;
        private SharedPreferences savednotes;
        private EditText editText1;
    
        protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.x1);
    
            savenotebutton1 = (Button) findViewById(R.id.savenotebutton1);
            editText1 = (EditText) findViewById(R.id.noteEditText1);
            savednotes = getSharedPreferences("notes",MODE_PRIVATE);
    
            editText1.setText(savednotes.getString("tag", "Default Value")); //add this line
    
            savenotebutton1.setOnClickListener(saveButtonListener);
        }
    
        private void makeTag(String tag){
           String or = savednotes.getString(tag, null);
            SharedPreferences.Editor preferencesEditor = savednotes.edit();
            preferencesEditor.putString("tag",tag); //change this line to this
            preferencesEditor.commit();
        }
    
        public OnClickListener saveButtonListener = new OnClickListener(){
    
            @Override
            public void onClick(View v) {
                if(editText1.getText().length()>0){
                makeTag(editText1.getText().toString());    
    
                ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(editText1.getWindowToken(),0);
    
                }
            }
        };
    }
    
    0 讨论(0)
提交回复
热议问题