N
N
Nikita2017-10-15 14:40:23
Java
Nikita, 2017-10-15 14:40:23

How can I do an element removal from SharedPreferences in my example?

I need the value to be deleted when the program is closed and when I go again, everything is as if from scratch

public void onClick(View view) {
        SharedPreferences sp = getSharedPreferences(MY_SETTINGS, Context.MODE_PRIVATE);
        boolean flag = sp.getBoolean("Flag",false);
        if(!flag){
            Log.d(LOG_TAG, "IF");
            //Timer
            new CountDownTimer(6000, 1000) {
                public void onTick(long millisUntilFinished) {
                    // mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
                }
                public void onFinish() {
                    window();
                    textView.setText("Timer out");
                }
            }.start();
            //Timer
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("Flag",true);
            editor.apply();
        }
        else{
            Log.d(LOG_TAG,"ELSE");
        }
    }
    @Override
    public void onDestroy(){
        Log.d(LOG_TAG,"onDestroy");
        SharedPreferences sp = getSharedPreferences(MY_SETTINGS, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove("Flag");
        editor.apply();
    }
    public void window(){
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Important message!")
                .setMessage("Timer out")
                .setCancelable(false)
                .setNegativeButton("Ok, shit",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Log.d(LOG_TAG,"onClick in window");
                                SharedPreferences sp = getSharedPreferences(MY_SETTINGS, Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor = sp.edit();
                                editor.remove("Flag");
                                editor.apply();
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2017-10-15
@zagayevskiy

If you need this, then you are doing something wrong. SPs are needed to save between application launches.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question