How can I refrence something between two activities? - android

So I am making this app and I want this settings page kind of thing where the user can choose if they want the sound on or off how do I reference the playsound method in the second activity?

As you mention settings I assume you use SharedPreferences -if not please do as it is the stander way to implement settings-, in this case, it is so easy to so:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean key = sharedPreferences.getBoolean("playsound", false);

I used a switch 'button' in my code to solve the same problem like u. here is an example
SharedPreferences pref;
SharedPreferences.Editor editor;
MediaPlayer backgroundmusik;
Switch mute;
View dummysetting;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.checksound_layout);
//SHARED PREFERENCES
pref = getSharedPreferences("your_label",MODE_PRIVATE);//label to find in Manifest
editor = pref.edit();
backgroundmusik = MediaPlayer.create(this,R.raw.dingdong);
dummysetting = (View) View.inflate(this, R.layout.setmute_layout,null); //you need that dummy, when u want to check ur button when u are on a different layout other way you get nullpointer.
mute=(Switch)dummysetting.findViewById(R.id.mute);
mute.setChecked(pref.getBoolean("Musik", true));//set true or false, its the 'status' when start for the first time after u install app.
if (mute.isChecked())
{
backgroundmusik = MediaPlayer.create(Hauptmenue.this,R.raw.dingdong);
backgroundmusik.setLooping(true);
backgroundmusik.start();
}
}//close oncreat
now you can set on an another place in the same activity the mute button like:
setContentView(dummysetting);
mute.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
backgroundmusik = MediaPlayer.create(MAinactivity.this,R.raw.dingdong);
backgroundmusik.setLooping(true);
backgroundmusik.start();
editor.putBoolean("Musik", true);
editor.commit();//safe the edit
}else
{
backgroundmusik.stop();
editor.putBoolean("Musik", false);
editor.commit();//safe the edit
}
}
});
}//close main.
That was just an example. i comy paste some codes from my code. If doesnt work you can ask again.
AND sharedpreferences can u use from every activity, when u declare and call them in the activity. Need just:
SharedPreferences pref;
SharedPreferences.Editor editor;
then in oncreat
pref = getSharedPreferences("your_label",MODE_PRIVATE);
editor = pref.edit();
and then when u safe as
editor.putBoolean("**Musik**", true);
editor.commit();//safe the edit
u have to ask for "Musik" again like:
pref.getBoolean("Musik", true)
to read.

Related

Save SWITCH button state, and recover state with SharedPrefs

I have a Settings class so the user can decide to subscribe/unsubscribe to channels in Parse Push.
I think I got it all figure out except for the part to recover, and maintain the switch state next time user open the app or changes the state.
Can someone please help me on how to save the state, and switch the SWITCH to what the user selected?
public class Settings extends Activity {
/**
* Called when the activity is first created.
*/
private Switch krspush, egspush;
public static final String PREFS_NAME = "SwitchButton";
krspush = (Switch) findViewById(R.id.krspush);
egspush = (Switch) findViewById(R.id.egspush);
SharedPreferences sharedPrefs = getSharedPreferences("SwitchButton", MODE_PRIVATE);
// How?
public void onKrsClick (View view) {
boolean on = ((Switch) view).isChecked();
if (on) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onKrsClick", true);
editor.commit();
ParsePush.subscribeInBackground("egersund");
} else {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onKrsClick", false);
editor.commit();
ParsePush.unsubscribeInBackground("egersund");
}
}
public void onEgsClick (View view) {
boolean on = ((Switch) view).isChecked();
if (on) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onEgsClick", true);
editor.commit();
ParsePush.subscribeInBackground("egersund");
} else {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onEgsClick", false);
editor.commit();
ParsePush.unsubscribeInBackground("egersund");
}
}
Override the onCreate method of that activity class and attempt to load the values you saved in SharedPreferences.
krspush.setChecked(sharedPrefs.getBoolean("onKrsClick",false));
findviewbyid will crash unless called after the view is created ie, in the oncreate method.
Consider using click listener on your switches.
I don't see the point of this line of code "SharedPreferences sharedPrefs = getSharedPreferences("SwitchButton", MODE_PRIVATE)"
Here is how you use shared preferences : https://stackoverflow.com/a/23024962/2590252
You better look into some samples to learn about best coding practices http://developer.android.com/samples/index.html

How to save (switch) button state in android?

I am using SWITCH (like android toggle button ) instead of normal buttons in my andorid app.
The code works fine while enabling and disabling switches.
But i want to store the state of the switch.
Suppose i enable the switch and close my application the background code will run fine but the switch state will change to disabled.
Every time when i close the application the switch state becomes disabled.
Is there any way to store the switch State??
Use shared preferences or a database to store the state of your switch. It is essential that you depend on the lifecycle methods of Activity/fragment.
The following might help you:
#Override
public void onClick(View v)
{
if (toggle.isChecked())
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", true);
editor.commit();
}
else
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", false);
editor.commit();
}
}
The final nail:
#Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyle", MODE_PRIVATE);
toggle.setChecked(sharedPrefs.getBoolean("NameOfThingToSave", true));
}
Edit:
The above code is working, however I feel it is a bad practice to get the shared preference values in onCreate, its better to make a loader class which inits your app variables well beforehand in a separate thread.
Update: Wed 24 Jul; 2019:
Android has view model support now - this can be used to handle switch state and persist it across sessions or configuration changes.
SharedPreferences pref = getSharedPreferences("save",MODE_PRIVATE);
unit.setChecked(pref.getBoolean("first", false));
if(isChecked) {
SharedPreferences.Editor editor = getSharedPreferences("save"MODE_PRIVATE).edit();
editor.putBoolean("first", true);
editor.apply();
unit.setChecked(true);}
else
{
SharedPreferences.Editor editor = getSharedPreferences("save",MODE_PRIVATE).edit();
editor.putBoolean("first",false);
editor.apply();
kilometer.setText("Km/h");
unit.setChecked(false);`enter code here`
}

Saving checkbox state using SharedPreferences

how do i save a checkbox state in activity B so that when i go back to activity A , it will show an appropriate response?
I am trying to make a function such that when a checkbox state in Activity B is checked , it will go back to A and play music , and this preference will be saved so that when the app is killed and relaunched , the preference stays.
You can save a boolean in SharedPreferences. It's clearly explained here: http://developer.android.com/training/basics/data-storage/shared-preferences.html
On Activity B you need to set preference depends on the CheckBox state
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
SharedPreferences sharedPref = getBaseContext().getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("checked", isChecked);
editor.commit();
}
});
On Activity A you need to get the preference value as follow
SharedPreferences sharedPref = context.getSharedPreferences("mypref", Context.MODE_PRIVATE);
boolean isChecked = sharedPref.getBoolean("checked", false); // false if it's not exist
Implement OnSharedPreferenceChangeListener in your activity B and override onSharedPreferenceChanged method
Here's my code
#Override
public void onSharedPreferenceChanged(SharedPreferences preferences,String arg1) {
// TODO Auto-generated method stub
preferences = PreferenceManager.getDefaultSharedPreferences(this);
checkbox = preferences.getBoolean("checkbox", false);
if(checkbox){
//Do your stuff here like playing music
Log.d("checkbox", "check enabled");
Intent myIntent = new Intent(ActivityB.this, ActivityA.class);
startActivity(myIntent);
}

android using shared preferences issue

static int existingCounter;
Context mContext = SplashScreen.getContextOfApplication();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
public static int cCounter()
{
MainMenu mm = new MainMenu();
existingCounter = mm.getExistingCounter();;
return existingCounter;
}
public void setSharedPreferences(int count)
{
SharedPreferences preferences = mContext.getApplicationContext().getSharedPreferences("myCounter", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("existingCount", existingCounter);
editor.commit();
}
//Get value from shared preferences
public int getExistingCounter()
{
SharedPreferences myPrefs = mContext.getApplicationContext().getSharedPreferences("myCounter", 0);
myPrefs.getInt("existingCount", 0);
return existingCounter ;
}
Hi all, above is my shared preferences. What I am trying to achieve is when user 1st launch the app, my app shall direct user to the disclaimer page and after the user agree to the T&C then in future the user launch the app shall not show the disclaimer page again. However, my current codes only valid when user never exit app. If the user were to exit the app and relaunch, my app still shows the disclaimer page. Please assist =) Thank you in advance. Below is the part where I set the sharedpreferences:
case 3:
cCounter();
if(existingCounter==0)
{
changeMenuFrag(new AcknowledgePg());
existingCounter++;
setSharedPreferences(existingCounter);
}
else
{
changeMenuFrag(new GalleryMain());
}
break;
Save a flag in the Preferences when you start up the application, after you've done the welcome screen stuff. Check for this flag before you show the T&C screen. If the flag is present (in other words, if it's not the first time), don't show it. Instead of a integer counter use a boolean flag and in your main activity check if the flag is true or false based on that show the appropriate activity.
SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// second argument is the default to use if the preference can't be found
Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);
if (!welcomeScreenShown) {
// here you can launch another activity if you like
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, true);
editor.commit(); // Very important to save the preference}
}

Android: How do I create a function that will be executed only once?

How can i create a function that will be run only once, on first installation? I am trying to create an information that displays one time.
thanks in advance.
You could use a flag in the shared preferences.
Then on every startup you check this flag. If it is not set you display your first time message and then set the flag.
For example:
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean firstStart = settings.getBoolean("firstStart", true);
if(firstStart) {
//display your Message here
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstStart", false);
editor.commit();
}
}

Categories

Resources