如何将textview设置为sharedpreference值

时间:2016-08-25 11:54:28

标签: java android

您好我想知道如何从android

调用会话

以下是我的登录页面的代码,其中设置了会话

Runnable runnable = new Runnable() {
        public void run() {
            Users user = mapper.load(Users.class,username);

           // System.out.println(user.getPassword());
           // System.out.println(username);
            try {
                if (user != null && user.getPassword().equals(password)) {
                    //System.out.println("Correct");
                    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
                    SharedPreferences.Editor editor = pref.edit();
                    editor.putString("userSession", username);
                    editor.commit();

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //setContentView(R.layout.activity_account);
                            startActivity(new Intent(startActivity.this, accountActivity.class));
                        }
                    });

登录后进入帐户页面,accound页面的代码如下所示

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_account);
      /* SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
    SharedPreferences.Editor editor = pref.edit();

    String User=pref.getString("userSession", "Not Exist");
    System.out.println("Hello");
    System.out.println(User);
*/
    test = (Button) findViewById(R.id.streamingButton);
    testId = (TextView)findViewById(R.id.welcomeTxt);
}

现在我想知道如何将textview设置为登录用户的用户名我已经评论了共享偏好代码,因为它不打印用户ID。我不明白为什么评论的代码不起作用

4 个答案:

答案 0 :(得分:1)

您不需要使用SharedPreferences,只需将数据置于意图中。然后,您可以在accountActivityCreate上获取数据表单。 见:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_account);

    Intent intent = getIntent();
    String userName = intent.getStringExtra("userName");

    test = (Button) findViewById(R.id.streamingButton);
    testId = (TextView)findViewById(R.id.welcomeTxt);

}

答案 1 :(得分:0)

您可以使用setText()方法轻松更改文本视图的值。或者您可以使用append()将文本添加到末尾(不覆盖现有值)。

testId.setText("my value");

我不太清楚为什么SharedPreferences不起作用。获取应用程序上下文的代码是否可以从Runnable对象中运行?你需要将一个上下文传递给Runnable吗?

答案 2 :(得分:0)

请使用apply代替以共享首选项保存数据的提交。请仅删除行SharedPreferences.Editor editor = pref.edit();并取消注释您的代码。这将为您提供共享偏好中的正确值存储。

答案 3 :(得分:0)

account page编辑为此内容!

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);

    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
    if(pref.contains("userSession") {

         String user = pref.getString("userSession", "UNDEFINED");
         textview.setText(user);

    }
}