简体   繁体   中英

sharedpreferences getString () returns the empty string in activity three

I have three activities, LoginActivity.java

public class LoginActivity extends AppCompatActivity {

TextView txtDaftar;
Button btnLogin;
EditText inputEmail, inputPassword;

// creating constant keys for shared preferences.
public static final String SHARED_PREFS = "sahabattani";

// key for storing user_id.
public static final String USER_ID_KEY = "user_id_key";

// key for storing email.
public static final String EMAIL_KEY = "email_key";

// key for storing nama.
public static final String NAMA_KEY = "nama_key";

// key for storing role.
public static final String ROLE_KEY = "role_key";

// variable for shared preferences.
SharedPreferences sharedpreferences;
String userId, email, nama, role;

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

    btnLogin = findViewById(R.id.btnLogin);
    txtDaftar = findViewById(R.id.gotoRegister);
    inputEmail = findViewById(R.id.inputEmail);
    inputPassword = findViewById(R.id.inputPassword);

    // getting the data which is stored in shared preferences.
    sharedpreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
    userId = sharedpreferences.getString(USER_ID_KEY, "");
    email = sharedpreferences.getString(EMAIL_KEY, "");
    nama = sharedpreferences.getString(NAMA_KEY, "");
    role = sharedpreferences.getString(ROLE_KEY, "");

    txtDaftar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    });

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (TextUtils.isEmpty(inputEmail.getText().toString()) || TextUtils.isEmpty(inputPassword.getText().toString())){
                Toast.makeText(LoginActivity.this,"Email / Password Required", Toast.LENGTH_LONG).show();
            }else{
                // Proses login
                login();

            }
        }
    });
}

public void login(){
    LoginRequest loginRequest = new LoginRequest();
    loginRequest.setEmail(inputEmail.getText().toString());
    loginRequest.setPassword(inputPassword.getText().toString());

    Call<LoginResponse> loginResponseCall = ApiClient.getUserService().userLogin(loginRequest);
    loginResponseCall.enqueue(new Callback<LoginResponse>() {
        @Override
        public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
            if (response.isSuccessful()){
                Toast.makeText(LoginActivity.this,"Login Successful", Toast.LENGTH_LONG).show();
                LoginResponse loginResponse = response.body();

                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString(USER_ID_KEY, loginResponse.getUserId());
                editor.putString(EMAIL_KEY, loginResponse.getEmail());
                editor.putString(NAMA_KEY, loginResponse.getNama());
                editor.putString(ROLE_KEY, loginResponse.getRole());
                editor.apply();

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (loginResponse.getRole().equals("petani")){
                            Intent intent = new Intent(LoginActivity.this, DashboardActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }else{
                            Intent intent = new Intent(LoginActivity.this, DashboardActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                    }
                },700);
            }else{
                Toast.makeText(LoginActivity.this,"Login Failed", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(Call<LoginResponse> call, Throwable t) {
            Toast.makeText(LoginActivity.this,"Throwable "+t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
    });

}
}

DashboardActivity.java

public class DashboardActivity extends AppCompatActivity {

private AppBarConfiguration mAppBarConfiguration;

// creating constant keys for shared preferences.
public static final String SHARED_PREFS = "sahabattani";

// key for storing user_id.
public static final String USER_ID_KEY = "user_id_key";

// key for storing email.
public static final String EMAIL_KEY = "email_key";

// key for storing nama.
public static final String NAMA_KEY = "nama_key";

// key for storing role.
public static final String ROLE_KEY = "role_key";

// variable for shared preferences.
SharedPreferences sharedpreferences;
String userId, email, nama, role;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    NavigationView navigationView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    mAppBarConfiguration = new AppBarConfiguration.Builder(
            R.id.nav_home, R.id.nav_find_tengkulak, R.id.nav_price, R.id.nav_forecast, R.id.nav_marketplace, R.id.nav_info)
            .setDrawerLayout(drawer)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
    NavigationUI.setupWithNavController(navigationView, navController);

    // initializing our shared preferences.
    sharedpreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);

    // getting data from shared prefs and
    // storing it in our string variable.
    userId = sharedpreferences.getString(USER_ID_KEY, "");
    email = sharedpreferences.getString(EMAIL_KEY, "");
    nama = sharedpreferences.getString(NAMA_KEY, "");
    role = sharedpreferences.getString(ROLE_KEY, "");

    View headerView = navigationView.getHeaderView(0);
    TextView headerNama = (TextView) headerView.findViewById(R.id.header_nama);
    TextView headerEmail = (TextView) headerView.findViewById(R.id.header_email);
    ImageView imgProfil = (ImageView) headerView.findViewById(R.id.vwProfil);

    headerNama.setText(nama);
    headerEmail.setText(email);
    imgProfil.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(DashboardActivity.this, ProfileActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.dashboard, menu);
    return true;
}

@Override
public boolean onSupportNavigateUp() {
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    return NavigationUI.navigateUp(navController, mAppBarConfiguration)
            || super.onSupportNavigateUp();
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if (item.getItemId() == R.id.action_logout) {
        // calling method to edit values in shared prefs.
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.clear();
        editor.apply();

        Intent intent = new Intent(DashboardActivity.this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        return true;
    }
    return super.onOptionsItemSelected(item);

}
}

and ProfileActivity.java

public class ProfileActivity extends AppCompatActivity {

// creating constant keys for shared preferences.
public static final String SHARED_PREFS = "sahabattani";
// key for storing user_id.
public static final String USER_ID_KEY = "user_id_key";

TextView editNama, editEmail, editDesa, editKecamatan, editKabupaten, editProvinsi;
Button btnUpdate;

// variable for shared preferences.
SharedPreferences sharedpreferences;
String userId;

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

    if (getSupportActionBar() != null) {
        getSupportActionBar().setTitle("Profil");
    }

    // initializing our shared preferences.
    sharedpreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
    userId = sharedpreferences.getString(USER_ID_KEY, "");

    // Call function getProfile()
    getProfile(userId);

    editNama = findViewById(R.id.edit_nama);
    editEmail = findViewById(R.id.edit_email);
    editDesa = findViewById(R.id.edit_desa);
    editKecamatan = findViewById(R.id.edit_kecamatan);
    editKabupaten = findViewById(R.id.edit_kabupaten);
    editProvinsi = findViewById(R.id.edit_provinsi);
    btnUpdate = findViewById(R.id.btn_update);
}

public void getProfile(String userId){
    GetProfileRequest getProfileRequest = new GetProfileRequest();
    getProfileRequest.setUser_id(userId);

    Call<GetProfileResponse> getProfileResponseCall = ApiClient.getUserService().userProfile(getProfileRequest);
    getProfileResponseCall.enqueue(new Callback<GetProfileResponse>() {
        @Override
        public void onResponse(Call<GetProfileResponse> call, Response<GetProfileResponse> response) {
            if (response.isSuccessful()){
                GetProfileResponse getProfileResponse = response.body();
                editNama.setText(getProfileResponse.getNama());
                editEmail.setText(getProfileResponse.getEmail());
                editDesa.setText(getProfileResponse.getDesa());
                editKecamatan.setText(getProfileResponse.getKecamatan());
                editKabupaten.setText(getProfileResponse.getKabupaten());
                editProvinsi.setText(getProfileResponse.getProvinsi());
            }
        }

        @Override
        public void onFailure(Call<GetProfileResponse> call, Throwable t) {
            Toast.makeText(ProfileActivity.this,"Throwable "+t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
        }
    });
}
}

The problem is that when the application moves from LoginActivity to DashboardActivity, I can retrieve the values stored in the sharedpreference. But when I move from DashboardActivity to ProfileActivity I can't get the stored value and when I call the getString () function it returns the default value which is an empty string. What is wrong?

see your function onOptionsItemSelected in DashboardActivity

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if (item.getItemId() == R.id.action_logout) {
        // calling method to edit values in shared prefs.
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.clear();
        editor.apply();

        Intent intent = new Intent(DashboardActivity.this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        return true;
    }
    return super.onOptionsItemSelected(item);

}

you clear SharedPreferences in this function when use

 SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.clear();
    editor.apply();

and its normal you cant get any data from any where from SharedPreferences when you clear it!

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