3

How can I use savePreferences and loadPreferences methods In first activity

private static final String GLOBAL_PREFERENCES = "music_status";

public static void savePreferences(@NonNull Context context, String key, int value) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt(key, value);
    editor.apply();
}...
protected void onResume() {
    super.onResume();

    musicGroup = (RadioGroup) findViewById(R.id.radioGroupForMusic);
    turnOn = (RadioButton) findViewById(R.id.radioButtonMusicOn);
    turnOff = (RadioButton) findViewById(R.id.radioButtonMusicOff);
    musicGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId){
                case R.id.radioButtonMusicOff:
                    mediaPlayer.pause();
                    savePreferences(MainMenuActivity.this,"music_status",0);
                case R.id.radioButtonMusicOn:
                    mediaPlayer.start();
                    savePreferences(MainMenuActivity.this,"music_status",1);
            }
        }
    });

}

In Second activity

private static final String GLOBAL_PREFERENCES = "music_status";
public static int loadPreferences(@NonNull Context context, String key, int defaultValue) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
    return sharedPreferences.getInt(key, defaultValue);
}

However I do not know how to get the value from first activity

Bohua Jia
  • 77
  • 8
  • 2
    What is that exception? Post logcat – Raghavendra Oct 18 '16 at 07:55
  • 1
    `MainMenuActivity.status`.. So this is a static variable? Note: Intents+Extras are recommended over static variables. – OneCricketeer Oct 18 '16 at 07:55
  • Try not to use an activity then. i would make a new class containing the needed values and have both activities implement that class. – selmaohneh Oct 18 '16 at 07:55
  • Could you explain how you have two activities but are not navigating between them? – OneCricketeer Oct 18 '16 at 08:00
  • Possible duplicate of [How do I pass data between activities on Android?](http://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-on-android) – Sergey Shustikov Oct 18 '16 at 08:03
  • This is the exception "FATAL EXCEPTION: main Process: loc.nwd.splitball, PID: 2506 java.lang.NullPointerException: Attempt to invoke virtual method 'void loc.nwd.splitball.musicStatus.setStatus(int)' on a null object reference" – Bohua Jia Oct 18 '16 at 08:49

3 Answers3

4

The short answer is you cannot do that. Unless your status variable is static. Which is extremely bad for this case.

You have three choices.

SharedPreferences

In contrast to my previous revision. This might be the best option for your case.

If you only want to save the state of something, you might find it better to simply not use a class to hold the status of your music. You could do as @cricket_007 suggests and implement SharedPreferences.

You could use these example functions:

private static final String GLOBAL_PREFERENCES = "a.nice.identifier.for.your.preferences.goes.here";

public static void savePreferences(@NonNull Context context, String key, int value) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt(key, value);
    editor.apply();
}

public static int loadPreferences(@NonNull Context context, String key, int defaultValue) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(GLOBAL_PREFERENCES, Context.MODE_PRIVATE);
    return sharedPreferences.getInt(key, defaultValue);
}

You can then use those functions in your code to save the status of your music. Instead of status.setStatus(0); and status.setStatus(1); your can use Utils.savePreferences(context, "music_status", 1); and instead of status.getStatus() you could use Utils.loadPreferences(context, "music_status", 0);

Parcelable

One option for you is to implement Parcelable in your musicStatus class. You can then send the object through an Intent to your second activity. You may find an example class implementing Parcelable below.

Once you have that, you can pass it through Intents like so:

musicStatus status = new musicStatus();
status.setStatus(8);
Intent intent = new Intent(this, HighScoreActivity.class);
intent.putExtra("status", status);
startActivity(intent);

Class implementation:

public class musicStatus implements Parcelable {
    private int status;

    public int getStatus() {
        return status;
    }

    public void setStatus(int status){
        this.status = status;
    }

    private musicStatus(Parcel in) {
        status = in.readInt();
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(status);
    }

    public static final Parcelable.Creator<musicStatus> CREATOR = new Parcelable.Creator<musicStatus>() {
        public musicStatus createFromParcel(Parcel in) {
            return new musicStatus(in);
        }

        public musicStatus[] newArray(int size) {
            return new musicStatus[size];
        }
    };

    public int describeContents() {
        return 0;
    }
}

Singleton

In this case, this would really be an anti-pattern. However, it is still a possibility.

public class musicStatus {
    private static musicStatus mInstance = null;
    private int status;

    @NonNull
    public static musicStatus getInstance() {
        if (mInstance == null) {
            synchronized(mInstance) {
                if (mInstance == null) {
                    mInstance = new musicStatus();
                }
            }
        }
    }

    public int getStatus(){
        return status;
    }

    public  void setStatus(int status){
        this.status = status;
    }
}
Knossos
  • 15,802
  • 10
  • 54
  • 91
  • 1
    `SharedPreferences` would be another potential option – OneCricketeer Oct 18 '16 at 07:59
  • yes, "public static musicStatus status;" I forgot to paste – Bohua Jia Oct 18 '16 at 08:45
  • Don't do that @BohuaJia: That will cause the `Activity` `Context` to leak. Since the static `musicStatus` will be referenced permanently! – Knossos Oct 18 '16 at 08:45
  • I am just learn android, can u tell me how to use `public class musicStatus implements Parcelable` thank u very much – Bohua Jia Oct 18 '16 at 08:53
  • @BohuaJia Please re-read my answer. I modified it. I added a reference to SharedPreferences, because it might well be better suited to your particular requirements. I also added a more fleshed out guide to Parcelable. – Knossos Oct 18 '16 at 09:08
  • in shared preference, what is the value of context? thank you – Bohua Jia Oct 18 '16 at 09:26
  • `Context` can be the `Activity` you are currently in. If you are in your `Activity` most of the time `this` will work. In a pinch however, something like `MainMenuActivity.this` will work too. The `Context` class is extremely important. It is worth reading about as part of your learning about Android: https://developer.android.com/reference/android/content/Context.html – Knossos Oct 18 '16 at 09:28
  • Have no idea how to use loadPreference, as I saw the int variable defaultValue, but I have no idea how to set it, I just up load my question – Bohua Jia Oct 18 '16 at 09:40
  • I really can't make it simpler than I have. Unless you have a more targetted question, this is about as far as I can help you. – Knossos Oct 18 '16 at 09:45
2

For the easiest way, your musicStatus class need implement Serializable.

Bundle bundle = new Bundle();
bundle.putSerializable("musicStatus", status);
intent.putExtras(bundle);

in other activity:

Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();

musicStatus status=
               (musicStatus)bundle.getSerializable("musicStatus");
PLe
  • 137
  • 4
0

extend Serviceable in you POJO class.

After while starting Activity 2.

  intetn.putExtra("obj",pojoObj);

and get it in you second activity using.

PojoCls obj = (PojoCls)getIntent().getSerializableExtra("obj");

Thats it.

Prashant Jajal
  • 3,469
  • 5
  • 24
  • 38