Unable to set SharedPreferences in AsyncTask?

I’m trying to set the shared preferences in my asynctask but it seems to not be working. Could anyone help me out. I tried a billion things already

Button/ASYNC Code:

button.setOnClickListener(new OnClickListener(){
        private ProgressDialog cancelDialog = null;
        int valid;

        public void onClick(View arg0) {
            new AsyncTask() {
                protected Void doInBackground(Void... params) {
                    valid = api.validateLogin(username.getText().toString(), password.getText().toString());
                    return null;

                protected void onPreExecute() {
                    cancelDialog = new ProgressDialog(LoginActivity.this);
                    cancelDialog.setMessage("Validating Username & Password");


                protected void onPostExecute(Void result){
                    if(valid == 2){
                        SharedPreferences savedSession = getApplicationContext().getSharedPreferences("xdaeaf", Activity.MODE_PRIVATE);
                        savedSession.edit().putString("username", username.getText().toString());
                        try {
                            String passtext = MCrypt.bytesToHex(mcrypt.encrypt(password.getText().toString()));
                            savedSession.edit().putString("password", ""+passtext);
                    } catch (Exception e) {




My accessing code:

SharedPreferences savedSession = context.getSharedPreferences("xdaeaf", Activity.MODE_PRIVATE);
    String username = savedSession.getString("username", "");
    String password = savedSession.getString("password", "");
    System.out.println("username:"+username+" password:"+password);

I checked if I was passing on empty variables to the putSTring but it is passing values to it. Its just not saving. When I rerun the accessing code it just prints out “Username: password:”. The values are blank when trying to re access it.

savedSession.edit().putString("username", username.getText().toString());

Every call to edit() returns you a new Editor instance. So you get an instance, make a change and leave it alone. Then you get a second one and commit that without changes, which results in no value changes in the preferences.

Editor editor = savedSession.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", ""+passtext);
Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 移动开发 » Unable to set SharedPreferences in AsyncTask?

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录