如何使用共享首选项来保存名称

时间:2014-02-19 15:03:46

标签: android preferences

我正在尝试创建一个可以减少学校纸张使用量的应用程序,所以我需要老师在设置活动中写下他的名字,然后将他的名字显示在主​​要活动中 这是我使用textview显示名称

的活动
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String key = null; 
    setContentView(R.layout.activity_main);
    SharedPreferences sp = getSharedPreferences(key, Activity.MODE_PRIVATE);
    String name = sp.getString(key, "");
    TextView name2 = (TextView) findViewById(R.id.textView1);
    name2.setText(name);
}
public void onResume(View view) {
    String key = null; 
    SharedPreferences sp = getSharedPreferences(key, Activity.MODE_PRIVATE);
    String name = sp.getString(key, "");
    TextView name2 = (TextView) findViewById(R.id.textView1);
    name2.setText(name);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
public void save(View view){
    Intent intent = new Intent(this, MainActivity2.class);
    startActivity(intent);
}

这是输入要保存名称的活动:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_activity2);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main_activity2, menu);
    return true;
}
public void save2 (View view) {
    final String key = "placeKey";  
    EditText save = (EditText) findViewById(R.id.editText1);
    String save2 = save.getText().toString(); 
    SharedPreferences sp = getSharedPreferences(key, Activity.MODE_PRIVATE);
    SharedPreferences.Editor edt = sp.edit();
    edt.putString(key, save2);
    edt.commit();

    String name = sp.getString(key, "");
    TextView name2 = (TextView) findViewById(R.id.textView1);
    name2.setText(name);
}
public void hrag (View view){
    final String key = "placeKey"; 

       SharedPreferences sharedpreferences;
    SharedPreferences sp = getSharedPreferences(key, Activity.MODE_PRIVATE);
    String name = sp.getString(key, "");
    TextView name2 = (TextView) findViewById(R.id.textView1);
    name2.setText(name);

}

任何帮助都会很棒

1 个答案:

答案 0 :(得分:1)

要保存到SharedPreferences,请通过传递活动的SharedPreferences来创建Context实例,如下所示...

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putString("key", value);
prefsEditor.commit();

SharedPreferences检索如下...

prefsEditor.getString("key", "");