无法在共享首选项首选项中保存当前状态进度条

时间:2017-06-29 11:25:31

标签: android progress-bar sharedpreferences

我在SharedPreferences的进度条中保存当前状态时遇到问题。 这是我的代码。参加这项活动时出现问题,接下来出去活动时,进度条不会计入状态并保持不变。

    private UpdateQrCode updateQrCode;
    SharedPreferences sharedpreferences;
    private static final String TIME = "Time";

方法onCreate女巫

@Override
    protected void onCreate(Bundle savedInstanceState) {
...

 sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);

 if (sharedpreferences.contains(Time)) {
            int currentInterval = sharedpreferences.getInt(TIME, 0);
            progressBar.setMax(currentInterval);
            progressBar.setProgress(currentInterval);
        } else {
            interval = Integer.parseInt(intervalTotpDecrypt);
        }
}

@Override
    public void onBackPressed() {
        super.onBackPressed();
        if (updateQrCode != null) {
            updateQrCode.cancel(true);
        }
    }

//此类带有更新进度条的asyncTask

  private class UpdateQrCode extends AsyncTask<Void, Integer, Integer> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setMax(interval);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressBar.setProgress(values[0]);
            secondTimeTextView.setText(String.valueOf(values[0]));
        }

        @Override
        protected Integer doInBackground(Void... params) {

            for (int i = interval; i >= 0; i--) {
                publishProgress(i);

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }


        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);


            try {
                NewXorString = generateQrCodeString(otpDecrypt, path3Decrypt, intervalTotpDecrypt);
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }

            generateNewString = Cryptography.xorHex(NewXorString);

            UpdateQrCodeString(generateNewString);
            updateQrCode.execute();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            updateQrCode.cancel(true);
        }
    }

 //method with save to sharedPreference 

 public void saveStateProgressBar() {
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putInt(TIME, interval);
        editor.commit();
    }

1 个答案:

答案 0 :(得分:0)

您使用Editor在共享偏好设置中存储值吗? e.g

SharedPreferences.Editor editor = prefs.edit();
editor.putString("progress", loadingProgress);
editor.commit();