1

I'm very new to Android and recently I got caught up in a situation where I need to use SharedPreferences: I have a variable that is changed as the project goes, and the app starts in a different screen depending on the variable's value, for example if the value is 0 then the app should start in LoginManager.class and if it's 1 then it starts in MainActivity.class.

So whenever I login successfully the state changes to 1 (so I don't have to login each time) or if I log out state is 0.
Given this, of course the variable needs to be saved externally so the value is not lost, and retrieve it when I create the first screen.

So my logic was that I create a onDestroy method so when the screen closes whatever global variable "state" has is what the SharedPreference variable "sharedstate" is going to get (This is from my initial Activity):

private SharedPreferences sharedPref;
public static int state=0;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_first);
    pb = (ProgressBar) findViewById(R.id.pb);
    mContext = IntroManager.this;
    pb.setVisibility(ProgressBar.VISIBLE);
    CountDownTimer mCountDownTimer;
    pb.setProgress(i);
    sharedPref = mContext.getSharedPreferences("Apathy", Context.MODE_PRIVATE);
    getProfile();
    mCountDownTimer=new CountDownTimer(1500,1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            Log.v("Log_tag", "Tick of Progress"+ i+ millisUntilFinished);
            i++;
            pb.setProgress((int)i*100/(1500/1000));
        }

        @Override
        public void onFinish() {
            check();
            i++;
            pb.setProgress(100);
        }
    };
    mCountDownTimer.start();
}

@Override
protected void onDestroy (){
    super.onDestroy();
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putInt("sharedstate", 1);
    editor.commit();
}

private void getProfile() {
    String sharedstate = sharedPref.getString("state", "");
    state= Integer.parseInt(sharedstate);
}

public void check(){
    if(state == 0){
        Intent mcrIntent = new Intent(IntroManager.this, LoginManager.class);
        startActivity(mcrIntent);
        overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
    }else{
        if(state == 1){
            Intent mcrIntent = new Intent(IntroManager.this, MainActivity.class);
            startActivity(mcrIntent);
            overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
        }
    }
}

So I got caught up in a dilemma: if I put that same onDestroy method in all of my screens (since I can't predict where the app is going to close) does the same "sharedstate" change it's value or does it create a bunch of variables that are called Sharedstate? And are they saved in the same "Apathy" thing?

Filnor
  • 1,290
  • 2
  • 23
  • 28
Hillary Rj
  • 13
  • 4

3 Answers3

0

I believe this code will update the same value over and over and not make duplicates.

If you want to see what your shared prefs looks like you can take a look at this answer: How can I view the shared preferences file using Android Studio?

That being said, as Vivart wrote, it would be unnecessary to update the pref every time onDestroy is called, you should only need to update in on login success or on logout

Quinn
  • 7,072
  • 7
  • 39
  • 61
0

It will override the same value everytime an Activity calls onDestroy. SharedPreferences are own files saved on the phone they were created on. The Tag "Apathy" is the name of the file and "sharedstate" is the key for the saved value.

That is the power of SharedPreferences you can save primitive data pretty easily. But when the app gets uninstalled the preferences are also gone.

Maybe look for some videos and tutorials, there are plenty out there. The Documentation is also really helpfull (but sometimes hard to understand for beginners)

Tommy
  • 80
  • 6
0

In Case anyone is really looking for it i managed to do it, i created a new class that manages all of that and in this case called "Util_Preferencias":

package com.example.user.mkpos;

import android.content.Context;
import android.content.SharedPreferences;
import static com.example.user.mkpos.IntroManager.state;


public class Util_Preferencias {

    Context miContexto;
    private SharedPreferences PreferenciasConfiguaracion;
    private  SharedPreferences.Editor editorPrefConfig;

    public Util_Preferencias(Context elContexto){
        miContexto=elContexto;
        PreferenciasConfiguaracion = miContexto.getSharedPreferences("PrefConfig",miContexto.MODE_PRIVATE);
        editorPrefConfig = PreferenciasConfiguaracion.edit();
    }


    public void GuardaPrefConfig(String estado){
        editorPrefConfig.putString("estado",estado);
        editorPrefConfig.commit();
    }

    public void CargaPref_Configuracion(){
        SharedPreferences prefs = miContexto.getSharedPreferences("PrefConfig",miContexto.MODE_PRIVATE);
        state = Integer.parseInt(prefs.getString("estado","0"));
    }

}

Whenever i needed to give state a new value i called GuardaPrefConfig and when i needed to retrieve i used CargaPref_Configuracion (by calling the class Uitl_Activity in the wanted activity like this:)

Util_Preferencias UtilPreferencias = new Util_Preferencias(getApplicationContext());
Hillary Rj
  • 13
  • 4