未从共享首选项获得值textview。 查看代码。 是否有任何错误。 而正是在下面的代码两行之间的区别...显示在共享首选项中输入的值未显示在textView中
sharedPreferences = getSharedPreferences("Mypreferences",Context.MODE_PRIVATE);
和
sharedPreferences=PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
以下是我的代码行..
public class MainActivity extends AppCompatActivity {
EditText et_name, et_phon, et_email, et_city;
Button button_submit, button_show;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
TextView tv_name,tv_phone,tv_email,tv_city;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initComponents();
sharedPreferences = getSharedPreferences("Mypreferences", Context.MODE_PRIVATE);
button_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name, phon, email, city;
name = et_name.getText().toString().trim();
phon = et_phon.getText().toString().trim();
email = et_email.getText().toString().trim();
city = et_city.getText().toString().trim();
editor = sharedPreferences.edit();
editor.putString("NameKey", name);
editor.putString("phoneKey", phon);
editor.putString("emailKey", email);
editor.putString("cityKey", city);
editor.apply();
Toast.makeText(MainActivity.this, "Submitted", Toast.LENGTH_SHORT).show();
}
});
button_show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
String n = sharedPreferences.getString("NameKey", null);
String p = sharedPreferences.getString("phoneKey", null);
String e = sharedPreferences.getString("emailKey", null);
String c = sharedPreferences.getString("cityKey", null);
tv_name.setText(n);
tv_phone.setText(p);
tv_email.setText(e);
tv_city.setText(c);
Toast.makeText(MainActivity.this, "Show button clicked", Toast.LENGTH_SHORT).show();
}
});
}
private void initComponents() {
et_name = (EditText) findViewById(R.id.et_name_main);
et_phon = (EditText) findViewById(R.id.et_phone_main);
et_email = (EditText) findViewById(R.id.et_email_main);
et_city = (EditText) findViewById(R.id.et_city_main);
tv_name = (TextView) findViewById(R.id.tv_name_main);
tv_phone = (TextView) findViewById(R.id.tv_phone_main);
tv_email = (TextView) findViewById(R.id.tv_email_main);
tv_city = (TextView) findViewById(R.id.tv_city_main);
button_submit = (Button) findViewById(R.id.btn_submit_main);
button_show = (Button) findViewById(R.id.btn_view_main);
}
}
任何类型的帮助表示赞赏。
这只是创建两个不同的sharedPreferences.xml。默认情况下,在您的应用程序directoy中命名为shared_preferences,另一个在您的情况下使用“mypreferences”命名。 MODE_PRIVATE表示没有其他应用可以输入它。 – Opiatefuchs
您正在保存在SharedPreferences的不同实例中,并在缺省情况下进行检索。在放置和检索时,使用'getSharedPreferences(“Mypreferences”,Context.MODE_PRIVATE)'或默认值。 – VenomVendor
Thanxx。在这个论据中,你们清楚了我的观点,我想知道关于MODES的事情。 –