简体   繁体   中英

How to compare EditText1 of MainActivity with EditText2 of SecondActivity (SharedPreferences)?

I have 2 EditTexts. EditText1 is in MainActivity, EditText2 is in SecondActivity. EditText1 is to login (password), EditText2 is to change password.

My code looks like this:

EditText editText1 = findViewById(R.id.login);
         editText2 = findViewById(R.id.changePassword); // declared in SecondActivity

if (editText1.getText().toString().equals(editText2.getText().toString())
{
  Intent intent = new Intent (MainActivity.this, SecondActivity.class);
  startActivity(intent);
}
else
{
  Toast.makeText(MainActivity.this, "Password incorrect", Toast.Length_Long).show;
}

When I press Button to login, it shows me an error. I know it has to be initialized in a different way but how?

I tried another code with a Dialog and everything worked perfectly:

changePasswordDialog = new Dialog(MainActivity.this);
changePasswordDialog.setContentView(R.layout.activity_second_activity);

editText2 = changePasswordDialog.findViewById(R.id.changePassword);

So it works perfectly with Dialog, but how does it work without Dialog?

Try Like this Store edit text 2 pass

    String pass = editText2.getText().toString().trim();
  SharedPreferences.Editor editor = getSharedPreferences(My_Prefs,Context.MODE_PRIVATE).edit();

editor.putString("pass", pass);
editor.apply();

Now Retrive the stored passwod in MainActivity

SharedPrefrences prefrences = getSharedPrefrences(My_Prefs,Context.MODE_PRIVATE);
String pass = prefrences.getString("pass","");
if (editText1.getText().toString().equals(pass)
{
  Intent intent = new Intent (MainActivity.this, SecondActivity.class);
  startActivity(intent);
}

You can use intent put extra and intent get extra for this

/// you can use this as per your requirement or you can use sharedprefrence///

// In main activity ///

Intent intent = new Intent (MainActivity.this, SecondActivity.class);
intent.putExtra("editText1",editText1.getText().toString());
startActivity(intent);

/// In second activity//

String passWord = getIntent().getExtras().getString("editText1");
Log.d("password : ",passWord);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM