繁体   English   中英

sharedpreferences getString() 返回活动三中的空字符串

[英]sharedpreferences getString () returns the empty string in activity three

我有三个活动, 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();
        }
    });

}
}

仪表板Activity.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);

}
}

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();
        }
    });
}
}

问题是当应用程序从 LoginActivity 移动到 DashboardActivity 时,我可以检索存储在 sharedpreference 中的值。 但是当我从 DashboardActivity 移动到 ProfileActivity 时,我无法获取存储的值,并且当我调用 getString () function 它返回默认值,即空字符串。 怎么了?

DashboardActivity中查看您的 function onOptionsItemSelected

@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);

}

您在使用时清除此 function 中的SharedPreferences

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

当您清除它时,您无法从SharedPreferences的任何地方获取任何数据,这很正常!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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