Android - SharedPreferences [closed]

0

My sharedPreferences is not working.

public static final String PREF_NAME = "TelaApresentacaoActivityPreferences";

       @Override
       protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_screen_slide);

       mPager = (ViewPager) findViewById(R.id.pager);
       mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
       mPager.setAdapter(mPagerAdapter);
       mPager.setOnPageChangeListener(newViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            invalidateOptionsMenu();
        }
    });

    sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
}

    @Override
    protected void onStop() {
    super.onStop();

    sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.commit();

}

    @Override
    protected void onDestroy() {
    super.onDestroy();

    sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear();
    editor.commit();

}

In my AndroidManifest.xml, I put code snippets in

 android:onHistory="true"
    
asked by anonymous 12.11.2015 / 15:00

1 answer

0

Every time the Activity is destroyed, the data is removed:

   @Override
    protected void onDestroy() {
    super.onDestroy();

    sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear();
    editor.commit();

}

comment this part:

 editor.clear();

To check if your app has already run, do the following:

           protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               setContentView(R.layout.activity_screen_slide);

               mPager = (ViewPager) findViewById(R.id.pager);
               mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
               mPager.setAdapter(mPagerAdapter);
               mPager.setOnPageChangeListener(newViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    invalidateOptionsMenu();
                }
            });

            sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);

boolean jaRodou = sharedPreferences.getBoolean("JaRodou", false);

if(jaRodou){
// se entrar aqui é pq já executou o codigo algiuma vez
}else{

            SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("JaRodou", true);
    editor.commit();
}
        }
    
12.11.2015 / 15:10