首页 > 解决方案 > 您如何将数据从只出现一次的活动切换到另一个总是出现的活动,您注册一次,然后只需要登录

问题描述

HActivity.java

    pass1 = (EditText) findViewById(R.id.edt1);
    pass1c = (EditText) findViewById(R.id.edt2);
    confirm = (TextView) findViewById(R.id.tv1);

    SharedPreferences pref = getSharedPreferences("Apref", Context.MODE_PRIVATE);
    if(pref.getBoolean("act_ex", false)){
        String passs11 = pass1.getText().toString();
        Intent intent = new Intent(this, LogInAct.class);
        intent.putExtra("PASSWW", passs11);
        startActivity(intent);
        finish();
    } else {
        SharedPreferences.Editor ed = pref.edit();
        ed.putBoolean("act_ex", true);
        ed.commit();
    }

// 它在 Android Studio 中使用 java,它会在您第一次打开应用程序时传递密码,但第二次这样做时,即使您输入正确的密码(您注册时使用的密码),它也会显示错误密码(如我所愿) ) 我怎样才能把它保存在某个地方或用它做些什么?

LogInAct.java

        tv2 = (TextView) findViewById(R.id.tv2);
        edt3 = (EditText) findViewById(R.id.edt3);

        Button loginbtn = (Button) findViewById(R.id.loginbtn);
        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logpass = edt3.getText().toString();
                passs1 = getIntent().getExtras().getString("PASSW");
                passs11 = getIntent().getExtras().getString("PASSWW");
            if (logpass.equals(passs1) && logpass.equals(passs11)) {
                Intent intent = new Intent(getApplicationContext(), Photos.class);
                startActivity(intent);
            } else {
                tv2.setText("wrong password");
            }


            }
        });

标签: javaandroidstringandroid-studio

解决方案


所以在我看来,在您的“注册”屏幕上,您正在捕获用户名和密码,然后将它们通过意图传递到登录屏幕?这在单个实例中效果很好,但不会持续存在。

仅从代码中很难分辨,但您如何在用户下次打开应用程序时将其带到登录屏幕?它只是在启动时进入那个屏幕吗?

在意图中传递的数据不会在会话之间保留。当仅针对该会话将数据从一个屏幕传递到另一个屏幕时,这是最有用的。

如果您有一个列表屏幕并且在下一个屏幕上是详细屏幕,则可以使用它。例如,您想传递他们单击的项目的 ID,以便您可以在该屏幕上加载数据。但是,如果他们关闭应用程序并再次打开它,则没有理由存储它。

要在会话之间持久化数据,您需要从更永久的存储中存储和提取数据。理想情况下,您最终会得到某种数据库系统。但是要回答您要执行的操作,请使用共享首选项来存储和提取密码。

登记:

SharedPreferences pref = getSharedPreferences("Apref", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("username", username);
editor.putString("password", password");
editor.apply();

登录:

SharedPreferences pref = getSharedPreferences("Apref", Context.MODE_PRIVATE);
passs1 = pref.getString("username");

同样,这绝对不是存储用户凭据的好方法,但它回答了您的持久性问题。


推荐阅读