在Android Studio中保存复选框状态(记住我)。

huangapple go评论72阅读模式
英文:

Save a checkbox state ( remember me) in android studio

问题

public class LoginActivity extends AppCompatActivity {

    // ... (other imports and class definition)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // ... (other code)

        Remember=findViewById(R.id.remember_me);

        // ... (other code)

        String email=sharedPreferences.getString("email","");
        String passwords=sharedPreferences.getString("mot de passe","");

        mEmail.setText(email);
        mPassword.setText(passwords);
        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // ... (other code)

                if(Remember.isChecked()){
                    editor.putString("email",mEmail.getText().toString());
                    editor.putString("passowrd",mPassword.getText().toString());
                    editor.commit();
                }else {
                    editor.putString("email", "");
                    editor.putString("passowrd", "");
                    editor.commit();
                }
                progressBar.setVisibility(View.VISIBLE);

                // ... (other code)

            }
        });

        // ... (other code)
    }
}
<!-- activity_login.xml -->

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bandeau_navigation"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:itemBackground="@color/noir"
        app:itemIconTint="@drawable/selector"
        app:itemTextColor="@drawable/selector"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0"
        app:menu="@menu/menu_navigation" />

    <androidx.core.widget.NestedScrollView
        android:id="@+id/scroll"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fillViewport="true"
        app:layout_constraintBottom_toTopOf="@+id/bandeau_navigation"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <View
                android:id="@+id/view3"
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:background="@drawable/saaalogo" />

            <EditText
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginTop="30dp"
                android:layout_marginEnd="16dp"
                android:background="@color/noir"
                android:ems="10"
                android:fontFamily="@font/futura_medium"
                android:hint="Email"
                android:padding="13dp"
                android:textColor="@color/blanc"
                android:textColorHint="@color/blanc"
                android:textSize="20sp" />

            <EditText
                android:id="@+id/password1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginTop="30dp"
                android:layout_marginEnd="16dp"
                android:background="@color/noir"
                android:ems="10"
                android:fontFamily="@font/futura_medium"
                android:hint="Mot de passe"
                android:inputType="textPassword"
                android:padding="13dp"
                android:textColor="@color/blanc"
                android:textColorHint="@color/blanc"
                android:textSize="20sp" />

            <CheckBox
                android:id="@+id/remember_me"
                android:layout_width="377dp"
                android:layout_height="34dp"
                android:layout_marginStart="16dp"
                android:layout_marginTop="5dp"
                android:layout_marginEnd="5dp"
                android:text="Se Souvenir de moi" />

            <!-- ... (other views) -->

        </LinearLayout>
    </androidx.core.widget.NestedScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
英文:

I would Like to save my checkbox always checked after the first checking, when the user presses it , the thing works but when i exit the app the check box is reseted , is there a way to prevent this? Now I have to check it again every time I move out the page login:

I want also to Log in only one time sow I dont have to repeat it each time I go out the application or when I come back to the login page

LoginActivity.java

public class LoginActivity extends AppCompatActivity {
EditText mEmail,mPassword;
TextView mCreateBtn,forgotTextLink;
Button mLoginBtn;
ProgressBar progressBar;
FirebaseAuth fAuth;
CheckBox Remember;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
BottomNavigationView bandeauNavigationView = findViewById(R.id.bandeau_navigation);
bandeauNavigationView.setSelectedItemId(R.id.accueil);
bandeauNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.accueil:
return true;
case R.id.commerce:
startActivity(new Intent(getApplicationContext(),PageCommercial.class));
overridePendingTransition(0,0);
return true;
case R.id.services:
startActivity(new Intent(getApplicationContext(),Support.class));
overridePendingTransition(0,0);
return true;
case R.id.info:
startActivity(new Intent(getApplicationContext(),Info.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
mEmail = findViewById(R.id.email);
mPassword = findViewById(R.id.password1);
progressBar = findViewById(R.id.progressBar1);
fAuth = FirebaseAuth.getInstance();
mLoginBtn = findViewById(R.id.loginBtn1);
mCreateBtn = findViewById(R.id.createText1);
forgotTextLink = findViewById(R.id.forgotPassword);
Remember=findViewById(R.id.remember_me);
////////////////////////////////////
Remember.isChecked();
sharedPreferences=getSharedPreferences(&quot;LoginPrefs&quot;, MODE_PRIVATE);
editor=sharedPreferences.edit();
/////////////////To get Stored Data/////////////////////////////////
progressBar.setVisibility(View.GONE);
String email=sharedPreferences.getString(&quot;email&quot;,&quot;&quot;);
String passwords=sharedPreferences.getString(&quot;mot de passe&quot;,&quot;&quot;);
mEmail.setText(email);
mPassword.setText(passwords);
mLoginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
if(TextUtils.isEmpty(email)){
mEmail.setError(&quot;Email manquant.&quot;);
return;
}
if(TextUtils.isEmpty(password)){
mPassword.setError(&quot;Mot de passe manquant.&quot;);
return;
}
if(password.length() &lt; 8){
mPassword.setError(&quot;Le mot de passe doit contenir au moins 8 caract&#232;res&quot;);
return;
}
if(Remember.isChecked()){
editor.putString(&quot;email&quot;,mEmail.getText().toString());
editor.putString(&quot;passowrd&quot;,mPassword.getText().toString());
editor.commit();
}else {
editor.putString(&quot;email&quot;, &quot;&quot;);
editor.putString(&quot;passowrd&quot;, &quot;&quot;);
editor.commit();
}
progressBar.setVisibility(View.VISIBLE);
// authenticate the user
fAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
@Override
public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
if(task.isSuccessful()){
startActivity(new Intent(LoginActivity.this,PageTechnique.class));
}else {
Toast.makeText(LoginActivity.this, &quot;Erreur ! &quot; + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
});
mCreateBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,Register.class));
}
});
forgotTextLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final EditText resetMail = new EditText(v.getContext());
final AlertDialog.Builder passwordResetDialog= new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle(&quot;R&#233;initialiser votre mot de passe ?&quot;);
passwordResetDialog.setMessage(&quot;Entrer votre Email pour recevoir un lien de r&#233;initialisation&quot;);
passwordResetDialog.setView(resetMail);
passwordResetDialog.setPositiveButton(&quot;Oui&quot;, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// extract the email and send reset link
String mail = resetMail.getText().toString();
fAuth.sendPasswordResetEmail(mail).addOnSuccessListener(new OnSuccessListener&lt;Void&gt;() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(LoginActivity.this, &quot;Un lien de r&#233;initialisation vous a &#233;t&#233; envoy&#233;&quot;, Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(LoginActivity.this, &quot;Erreur ! le lien de r&#233;initialisation n&#39;a pas &#233;t&#233; envoy&#233;&quot; + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton(&quot;Non&quot;, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// close the dialog
}
});
passwordResetDialog.create().show();
}
});
}
}

activity_login.xml

    &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout
xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;&gt;
&lt;com.google.android.material.bottomnavigation.BottomNavigationView
android:id=&quot;@+id/bandeau_navigation&quot;
android:layout_width=&quot;0dp&quot;
android:layout_height=&quot;wrap_content&quot;
app:itemBackground=&quot;@color/noir&quot;
app:itemIconTint=&quot;@drawable/selector&quot;
app:itemTextColor=&quot;@drawable/selector&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot;
app:layout_constraintVertical_bias=&quot;1.0&quot;
app:menu=&quot;@menu/menu_navigation&quot; /&gt;
&lt;androidx.core.widget.NestedScrollView
android:id=&quot;@+id/scroll&quot;
android:layout_width=&quot;0dp&quot;
android:layout_height=&quot;0dp&quot;
android:fillViewport=&quot;true&quot;
app:layout_constraintBottom_toTopOf=&quot;@+id/bandeau_navigation&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintHorizontal_bias=&quot;0.0&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot;
app:layout_constraintVertical_bias=&quot;1.0&quot;&gt;
&lt;LinearLayout
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
android:orientation=&quot;vertical&quot;&gt;
&lt;View
android:id=&quot;@+id/view3&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;200dp&quot;
android:background=&quot;@drawable/saaalogo&quot; /&gt;
&lt;EditText
android:id=&quot;@+id/email&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginStart=&quot;16dp&quot;
android:layout_marginTop=&quot;30dp&quot;
android:layout_marginEnd=&quot;16dp&quot;
android:background=&quot;@color/noir&quot;
android:ems=&quot;10&quot;
android:fontFamily=&quot;@font/futura_medium&quot;
android:hint=&quot;Email&quot;
android:padding=&quot;13dp&quot;
android:textColor=&quot;@color/blanc&quot;
android:textColorHint=&quot;@color/blanc&quot;
android:textSize=&quot;20sp&quot; /&gt;
&lt;EditText
android:id=&quot;@+id/password1&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginStart=&quot;16dp&quot;
android:layout_marginTop=&quot;30dp&quot;
android:layout_marginEnd=&quot;16dp&quot;
android:background=&quot;@color/noir&quot;
android:ems=&quot;10&quot;
android:fontFamily=&quot;@font/futura_medium&quot;
android:hint=&quot;Mot de passe&quot;
android:inputType=&quot;textPassword&quot;
android:padding=&quot;13dp&quot;
android:textColor=&quot;@color/blanc&quot;
android:textColorHint=&quot;@color/blanc&quot;
android:textSize=&quot;20sp&quot; /&gt;
&lt;CheckBox
android:id=&quot;@+id/remember_me&quot;
android:layout_width=&quot;377dp&quot;
android:layout_height=&quot;34dp&quot;
android:layout_marginStart=&quot;16dp&quot;
android:layout_marginTop=&quot;5dp&quot;
android:layout_marginEnd=&quot;5dp&quot;
android:text=&quot;Se Souvenir de moi&quot; /&gt;
&lt;Button
android:id=&quot;@+id/loginBtn1&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginStart=&quot;16dp&quot;
android:layout_marginTop=&quot;30dp&quot;
android:layout_marginEnd=&quot;16dp&quot;
android:background=&quot;@color/argent&quot;
android:fontFamily=&quot;@font/futura_medium&quot;
android:padding=&quot;15dp&quot;
android:text=&quot;Se Connecter&quot;
android:textSize=&quot;18sp&quot; /&gt;
&lt;TextView
android:id=&quot;@+id/createText1&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_gravity=&quot;center&quot;
android:layout_marginStart=&quot;16dp&quot;
android:layout_marginTop=&quot;20dp&quot;
android:layout_marginBottom=&quot;10dp&quot;
android:fontFamily=&quot;@font/futura_medium&quot;
android:padding=&quot;13dp&quot;
android:text=&quot;Non inscrit ? C&#233;er un compte&quot;
android:textColor=&quot;@color/noir&quot;
android:textSize=&quot;18sp&quot;
android:visibility=&quot;visible&quot; /&gt;
&lt;TextView
android:id=&quot;@+id/forgotPassword&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_gravity=&quot;center&quot;
android:layout_marginBottom=&quot;20dp&quot;
android:fontFamily=&quot;@font/futura_medium&quot;
android:text=&quot;Mot de passe oubli&#233; ?&quot;
android:textColor=&quot;@color/noir&quot;
android:textSize=&quot;18sp&quot;
android:textStyle=&quot;bold&quot; /&gt;
&lt;ProgressBar
android:id=&quot;@+id/progressBar1&quot;
style=&quot;?android:attr/progressBarStyle&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_gravity=&quot;center&quot;
android:layout_marginTop=&quot;8dp&quot;
android:layout_marginBottom=&quot;20dp&quot;
android:visibility=&quot;visible&quot; /&gt;
&lt;/LinearLayout&gt;
&lt;/androidx.core.widget.NestedScrollView&gt;
&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt; 

答案1

得分: 0

这个解决方案怎么样?

// 获取存储的数据
progressBar.setVisibility(View.GONE);
boolean isRemember = sharedPreferences.getBoolean("remember_me", false);
if (isRemember) {
String email = sharedPreferences.getString("email", "");
String passwords = sharedPreferences.getString("mot de passe", "");
mEmail.setText(email);
mPassword.setText(passwords);
Remember.setChecked(true);
}
mLoginBtn.setOnClickListener(new View.OnClickListener() {
// ...
if (Remember.isChecked()) {
editor.putBoolean("remember_me", true);
editor.putString("email", mEmail.getText().toString());
editor.putString("password", mPassword.getText().toString());
editor.commit();
} else {
// ...
英文:

How about this solution?

    /////////////////To get Stored Data/////////////////////////////////
progressBar.setVisibility(View.GONE);
**boolean isRemember=sharedPreferences.getBoolean(&quot;remember_me&quot;,false);**
**if(isRemember){**
String email=sharedPreferences.getString(&quot;email&quot;,&quot;&quot;);
String passwords=sharedPreferences.getString(&quot;mot de passe&quot;,&quot;&quot;);
mEmail.setText(email);
mPassword.setText(passwords);
**Remember.setChecked(true);**
**}**
mLoginBtn.setOnClickListener(new View.OnClickListener() {
......
if(Remember.isChecked()){
**editor.putBoolean(&quot;remember_me&quot;,true);**
editor.putString(&quot;email&quot;,mEmail.getText().toString());
editor.putString(&quot;passowrd&quot;,mPassword.getText().toString());
editor.commit();
}else {

huangapple
  • 本文由 发表于 2020年9月25日 15:19:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64059587.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定