如何在全局可访问文件的类中存储数据

时间:2014-01-02 20:20:17

标签: android

我正在尝试创建一个允许用户创建帐户并登录的基本应用程序。如何将此信息保存在所有类可全局访问的文件中?

我尝试使用SharedPreferences,并且能够存储信息但无法弄清楚如何检索它:

public void onClick(View v) {
                // TODO Auto-generated method stub
                EditText username = (EditText)findViewById(R.id.editText1);
                EditText password = (EditText)findViewById(R.id.editText2);
                EditText email = (EditText)findViewById(R.id.editText3);

                String usernameData = username.toString();
                String passwordData = password.toString();
                String emailData = email.toString();

                //How do I store data in java?

                if (username != null && password != null && email != null){
                    savePreferences("usernameKey", usernameData);
                    savePreferences("passwordKey", passwordData);
                    savePreferences("emailKey", emailData);
                    Intent nextpage =new Intent(accountcreation.this,    information.class);
                    startActivity(nextpage);

                }

1 个答案:

答案 0 :(得分:0)

要获取共享首选项,请在您的活动中使用以下方法:

SharedPreferences prefs = this.getSharedPreferences(
  "com.example.app", Context.MODE_PRIVATE);

阅读偏好:

String dateTimeKey = "com.example.app.datetime";

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime()); 

编辑和保存偏好

Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).commit();

取自:How to use SharedPreferences in Android to store, fetch and edit values