javaandroidsharedpreferencesshowcaseview

Sharedpreferences doesn't work in onCreateOptionsMenu


I try to display a showcase view that pointing to a menu item, but this sharedpreference just save before my app closed, after i close my app and open again showcase view will appear again. how i can show the showcase view only for the very first time?

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_contact, menu);

    pref = getSharedPreferences(String.valueOf(getApplicationContext()), Context.MODE_PRIVATE);
    editor = pref.edit();
    if (pref.getBoolean("isFirstTime", true)) {   // default true for first time
        editor.putBoolean("isFirstTime", false).commit(); // update  so it will false ever after
        new Handler().postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        mFancyShowCaseView = new FancyShowCaseView.Builder(ContactTabActivity.this)
                                .focusOn(findViewById(R.id.item_sync)) // ActionBar menu item id
                                .focusCircleRadiusFactor(1.5)
                                .focusBorderSize(15)
                                .focusBorderColor(Color.parseColor("#FFA64D"))
                                .customView(R.layout.case_view_sync, new OnViewInflateListener() {
                                    @Override
                                    public void onViewInflated(@NonNull View view) {
                                        view.findViewById(R.id.btnOke).setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                mFancyShowCaseView.removeView();
                                            }
                                        });
                                    }
                                }).closeOnTouch(false)
                                .build();
                        mFancyShowCaseView.show();
                    }
                }, 50
        );
    }
    editor.commit();
    return super.onCreateOptionsMenu(menu);
}

Solution

  • Instead of

    pref = getSharedPreferences(String.valueOf(getApplicationContext()), Context.MODE_PRIVATE);
    

    Use

    pref = getSharedPreferences("First_tym_check",Context.MODE_PRIVATE);
    

    This is because :-

    String.valueOf(getApplicationContext()) this string value is not CONSTANT

    If you restart the app, you will notice the value will change significantly like for instance :-

    So, the string value is different every time .