如何使用“共享首选项”存储文本视图

时间:2015-02-17 16:06:45

标签: java android android-intent sharedpreferences

所以我的问题可能已被多次询问,但我无法在互联网上的任何地方找到答案。

。我想要做的是使用sharedprefeences存储textview。

在我的第一堂课(xp)中,我将textview发送到另一个班级(反馈) 现在反馈回收文本视图没有任何问题,但从未保存。即使关闭应用程序后,如何将该textview存储在(反馈)类中?

这是意图使用textview

的类
public class Xp extends Activity {
Button accept;
TextView textV;
TextView xbnum;
public static final String PREFS_NAME = "MyPrefsFile";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.xp);
    accept = (Button) findViewById(R.id.accept);
    textV = (TextView) findViewById(R.id.textV);
    xbnum = (TextView) findViewById(R.id.xpnum);


    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String value1 = extras.getString("intent_xp");
        final String value = extras.getString("intent_extra");
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor edit = settings.edit();
        edit.putString(PREFS_NAME, value);
        edit.putString(PREFS_NAME,value1);

        textV.setText(value);
        xbnum.setText(value1);


        edit.commit();
        accept.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(Xp.this, feedback.class);
                i.putExtra("intent_extra", textV.getText().toString());
                startActivity(i);
                finish();
            }
        });


    }
}

}

这是一个将重现意图并保存textview的类(如假设的那样)

public class feedback extends Activity {
TextView test1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.feedback);
    test1 = (TextView) findViewById(R.id.test1);
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String value = extras.getString("intent_extra");
        SharedPreferences settings = getSharedPreferences("intent_pref", 0);
        SharedPreferences.Editor edit = settings.edit();
        edit.putString("intent_pref",value);
        test1.setText(value);
        edit.apply();

    }

}

}

班级正在回复文本,一切都很好。只有当我关闭应用程序并打开它时,一切都被清除了..

1 个答案:

答案 0 :(得分:0)

可能我错了,但似乎你错过了共享偏好的工作方式。

如果要在首选项文件中存储多个值,请在其他类中访问它,您必须创建一个SharedPreferences实例。

在你的情况下,它意味着在“反馈”和“Xp”中创建一个像这样的SharedPreferences实例:

SharedPreferences settings = getSharedPreferences("MyPrefsFile", SharedPreferences.MODE_PRIVATE);

然后使用此实例通过编辑器存储数据。 如果您无法为同一个密钥存储多个值,请务必小心。

您还可以像实际操作一样将值存储在多个文件中。但是,如果要使用首选项文件的值设置textview,则必须使用共享首选项实例上的getString("key_of_your_value")方法获取它。