简体   繁体   English

Android:共享首选项提供未知文本

[英]Android: shared preferences gives unknown text

So i need my app to save and remember the name that user enters in a search field.所以我需要我的应用程序来保存并记住用户在搜索字段中输入的名称。 I use shared preferences to do that.. But when i close the app and open again, instead of the saved name i get a text like this: android.support.AppCompatEditText{1f4bcb VEFD..Cl .F...197,800-860,927 app:id/username}我使用共享首选项来做到这一点..但是当我关闭应用程序并再次打开时,我得到的不是保存的名称,而是这样的文本:android.support.AppCompatEditText{1f4bcb VEFD..Cl .F...197,800-860,927应用程序:ID/用户名}

What am doing wrong?做错了什么?

  static SharedPreferences sharedPref;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);
  namefield = (EditText) findViewById(R.id.username); //this is the user-input field
  Tname = (TextView) findViewById(R.id.NameLabel); //this label will be the username when user press the UPDATEbtn
  UPDATEbtn = (Button)findViewById(R.id.Update_btn);

  // Get from the SharedPreferences
    sharedPref = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
    String USERname = sharedPref.getString("name", String.valueOf(0));
    Tname.setText(USERname);
}




//this is the onClick method of my UPDATEbtn
public void UpdateInfo(View view)
{

Tname.setText(namefield.getText());

    sharedPref = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("name", String.valueOf(namefield));

  // Apply the edits!
    editor.apply();


}

You are trying to access the edittext.您正在尝试访问编辑文本。

Try尝试

editor.putString("name", namefield.getText().toString()); editor.putString("name", namefield.getText().toString());

replace this line替换这一行

editor.putString("name", String.valueOf(namefield));

to

editor.putString("name",  namefield.getText().toString());

Actually you were not getting text of text field.实际上你没有得到文本字段的文本。

you should get edit view text and save that你应该得到编辑视图文本并保存

//change this line //改变这一行

 editor.putString("name", String.valueOf(namefield));

like below像下面

 editor.putString("name", String.valueOf(namefield.getText()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM