How I can use the shared preferences class?

57 views Asked by At

I use shared preference in my project to store user information, but I encounter problems that the program encounters an error and does not load at all, and in terms of code, there is no problem with my code. But the application does not come up, And the error text is not sent, so that I can put it to you, the application just closes and cannot be continued. How can I fix it?

This is the code of the class where I store the information:

public class UserManager {
private SharedPreferences sharedPreferences;

public UserManager(Context context) {
    sharedPreferences = context.getSharedPreferences("user_information", Context.MODE_PRIVATE);
}

public void saveUserInformation(String fullName, String email, String gender) {
    @SuppressLint("CommitPrefEdits") SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("full_name", fullName);
    editor.putString("email", email);
    editor.putString("gender", gender);
    editor.apply();
}

public String getFullName() {
    return sharedPreferences.getString("full_name", "");
}

public String getEmail() {
    return sharedPreferences.getString("email", "");
}

public String getGender() {
     return sharedPreferences.getString("gender", "");
   }

}

And this is the code of the main class that I receive the information after saving it:

public class MainActivity extends AppCompatActivity {

private UserManager userManager;
private String gender = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    userManager = new UserManager(this);

    TextInputEditText fullNameEt = findViewById(R.id.et_main_fullName);
    fullNameEt.setText(userManager.getFullName());
    TextInputEditText emailEt = findViewById(R.id.et_main_email);
    emailEt.setText(userManager.getEmail());
    RadioGroup genderRadioGroup = findViewById(R.id.radioGroup_main_gender);
    genderRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.btn_main_male) {
                gender = "male";
            } else {
                gender = "female";
            }
        }
    });
    gender = userManager.getGender();
    if (gender.equalsIgnoreCase("male")) {
        genderRadioGroup.check(R.id.btn_main_male);
    } else if (gender.equalsIgnoreCase("female")) {
        genderRadioGroup.check(R.id.btn_main_female);
    }
    View saveBtn = findViewById(R.id.btn_main_save);
    saveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            userManager.saveUserInformation(fullNameEt.getText().toString(),
                    emailEt.getText().toString(),
                    gender);
         }
     });

    }
}
0

There are 0 answers