如何使用共享首选项

时间:2019-03-22 21:04:54

标签: java android sharedpreferences

我想保存用户输入的登录值以保存在sharedpreferences中并在另一页中检索它。但是问题是当我去数据检索页面应用程序时崩溃了。请帮助我。

LoginActivity.java

 SharedPreferences loginData = getSharedPreferences("userInfo", 
 Context.MODE_PRIVATE);
 SharedPreferences.Editor editor = loginData.edit();
 editor.putString("password", passwordbox.getText().toString());
 editor.putString("userName", usernamebox.getText().toString());

 editor.apply();

数据检索页面

public class messagewebview extends AppCompatActivity {
    TextView testing_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_messagewebview);
        SharedPreferences loginData = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        String name = loginData.getString("userName", "");
        String pw = loginData.getString("password","");
        String msg = "Saved User Name: " + name + "\nSaved Password: " + pw;
        testing_name.setText(msg);

    }
}

2 个答案:

答案 0 :(得分:0)

testing_name未初始化。

答案 1 :(得分:0)

您的变量“ testing_name”未初始化。在开始使用变量之前,必须对其进行初始化。

执行以下代码更改。

    public class messagewebview extends AppCompatActivity { 

        TextView testing_name; 

        @Override protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_messagewebview);
          // Provide a appropriate view id
          testing_name = findViewById(R.id.testing_name);
          SharedPreferences loginData = getSharedPreferences("userInfo", Context.MODE_PRIVATE); 
          String name = loginData.getString("userName", ""); 
          String pw = loginData.getString("password","");
           String msg = "Saved User Name: " + name + "\nSaved Password: " + pw;
            testing_name.setText(msg);

        }

        }