i build an app, and in main menu i want to create a button to control whether the user wants to use music (unmute) or not (mute) only for this application (not the device) and the background music is played on another layout..
This is my method to call media player (in class Question.java):
public void playSound(int arg)
{
try
{
if(player != null)
{
if (player.isPlaying())
{
player.stop();
player.reset();
player.release();
}
}
}
catch(Exception e)
{
}
if (arg == 2)
{
player = MediaPlayer.create(this, R.raw.b);
}
if(player != null)
{
player.setLooping(true);
player.start();
}
}
And this is the code for the button (in my main menu, MainActivity.java):
public class MainActivity extends Activity
{
//another code.....
public String klik;
protected void onCreate(Bundle savedInstanceState)
{
//another code...
DataAdapter myDbHelper = new DataAdapter(this);
myDbHelper.createDatabase();
myDbHelper.open();
Cursor get = myDbHelper.getSound(1);
klik = Utility.GetColumnValue(get, "klik");
//to get value of klik on my database
if(klik.equals("1"))
{
setGbrSound(1);
//set button's background to mute
}
else if(klik.equals("2"))
{
setGbrSound(2);
//set button's background to unmute
}
myDbHelper.close();
//another code...
btnsuara.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(klik.equals("1"))
{
AudioManager aManager=(AudioManager)getSystemService(AUDIO_SERVICE);
aManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
setSound(2); //update klik value in database to klik=2
setGbrSound(2); //set button's background to unmute
setSound(3); //change value of String klik in this class from the value of klik in database
}
else if (klik.equals("2"))
{
AudioManager aManager=(AudioManager)getSystemService(AUDIO_SERVICE);
aManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
setSound(1); //update klik value in database to klik=1
setGbrSound(1); //set button's background to mute
setSound(3); //change value of String klik in this class from the value of klik in database
}
}
});
}
if i use this code in MainActivity.java, the function is working properly (i think it is because no media player to be played in this class). When the class Question.java is running, the method playSound is called and the media player is played. When i go back to the MainActivity.java and i choose to mute the music, and i go to the Question.java again, the background music is not played and then the Media volume setting for the device is disabled (not only for my application).
Anyone know how to solve this? Thx..
EDIT: i tried to use this code but it is still cannot be unmuted..
btnsuara.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(isMuted(mContext)==false)
{
AudioManager aManager =(AudioManager)getSystemService(AUDIO_SERVICE);
aManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
Editor editor = prefs.edit(); // get an Editor object
editor.putBoolean("isMuted", true); // set the mute boolean to true (mute)
editor.commit();
setGbrSound(2); //set button's background to unmute/sound on
}
else if (isMuted(mContext)==true)
{
AudioManager aManager=(AudioManager)getSystemService(AUDIO_SERVICE);
aManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
Editor editor = prefs.edit(); // get an Editor object
editor.putBoolean("isMuted", false); // set the mute boolean to false (unmute)
editor.commit();
setGbrSound(1); //set button's background to mute/sound off
}
}
});
public static boolean isMuted(Context c)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
return prefs.getBoolean("isMuted", false); // false is the default value
}
Any comments?
The fastest way:
1). Save the value as boolean or int or whatever in SharedPreferences
2). Check this value from anywhere in your app where you play music
You are done. Ask if you need some sample code
EDIT example:
In your menu Activity, define a Context as a class field (where you have all the other fields declared):
private Context mContext = this;
1). Then (in your onClick() method), set a boolean like:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
Editor editor = prefs.edit(); // get an Editor object
editor.putBoolean("isMuted", true); // set the mute boolean to true
editor.commit(); // save the changes
2). Perform the check from anywhere in your app by using this method (pass a valid Context). You can define and call this method in the Activity from which you want to check if the "mute" option was activated:
public static boolean isMuted(Context c){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
return prefs.getBoolean("isMuted", false); // false is the default value
}
Note that you can overwrite this value by using Editor.commit() method again
Related
I stored a value in my MainActivity called "tgpref".
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); //value to save
editor.commit();"
In my onCreate i have
public SharedPreferences preferences;
---
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preferences = getPreferences(MODE_PRIVATE);
I want to display the value in my widget so i try to write in the onUpdate in widget provider class this
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean tgpref = preferences.getBoolean("tgpref", false)
if (tgpref == true) {
remoteViews.setTextViewText(R.id.battery, "Risp on");
} else {
remoteViews.setTextViewText(R.id.battery, "Risp off");
}
If the toggle button in the MainActivty is clicked i want that in my widget appears "Risp on" else "Risp off". Right now displays only "Risp off" so i don't know how i can do. Any helps? Nothing happen i can't load the value
it looks good, so i guess your button doesn`t trigger the value change?!
MainActiviy
private Boolean mTgpref;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
//get value from shared preferences and update ui
prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
mTgpref = prefs.getBoolean("tgpref", false);
setYourText();
}
private void setYourTextAndStoreToSharedPref(){
Log.i("TEST","mTgpref -> " + mTgpref); //check value
if(mTgpref){
remoteViews.setTextViewText(R.id.battery, "Risp on");
}
else
{
remoteViews.setTextViewText(R.id.battery, "Risp off");
}
prefs.edit().putBoolean("tgpref", mTgpref).commit();
//UPDATE YOUR WIDGET HERE
}
//function called on switch button click
private void onSwitchClickButtonClick(){
mTgpref = !mTgpref; //toggle Boolean
setYourText();
}
EDIT
Sorry, I misunderstood your main problem. After updating SharedPreferences, you should follow the steps described here: http://developer.android.com/guide/topics/appwidgets/index.html#UpdatingFromTheConfiguration
I want to create a simple app to upload my location .I have two activities and in first activity the user can input parameters url for upload with editbox , a checkbox if user wish upload location save preferences button and start button for go to get location activity.I try this but no work...How i call my function start and save?Any help?I have errors when debug...after click button
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences preferences = getSharedPreferences("gpstracker" , MODE_PRIVATE);
String strValue = preferences.getString("Url",strValued);
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
edittxtUrl.setText(strValue);
Button buttonStart = (Button)findViewById(R.id.buttonStart);
buttonStart.setOnClickListener(startListener);
Button buttonSave = (Button)findViewById(R.id.buttonSave);
buttonSave.setOnClickListener(saveListener);
}
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v) {
Start();
}
};
private OnClickListener saveListener = new OnClickListener() {
public void onClick(View v) {
Save();
}
};
public void Save() {
SharedPreferences preferences = getSharedPreferences("gpstracker" , MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
String strUrl = edittxtUrl.getText().toString();
CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);
boolean blnTandC = chkTandC.isChecked();
editor.putString("Url", strUrl); // value to store
editor.putBoolean("TandC", blnTandC); // value to store
// Commit to storage
editor.commit();
}
public void Start() {
startActivity(new Intent(this, LocTracker.class));
}
Without your log cat it is somewhat hard to tell what your problem is, but what I think is happening is that you are passing a null view to the start method, and this is a problem because you are then trying to get a context. Effectively what you have written is
null.getContext()
which doesn't work. You can fix this by replacing view.getContext() with getApplicationContext()
I am storing the status of togglebutton using a sharedpreffrence.
I am putting "ON" if toggle button is checked and "OFF" if toggle button is unchecked.
But when I am retriveing the status , it always returns "ON"
Here is the code
SharedPreferences.Editor shfEditMessageSMS;
SharedPreferences shfResponderMessage;
shfResponderMessage=getSharedPreferences("MESSAGE", Context.MODE_PRIVATE);
shfEditMessageSMS=shfResponderMessage.edit();
toggleStatus=(ToggleButton)findViewById(R.id.toggleButtonStatus);
toggleStatus.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
if(((ToggleButton)v).isChecked())
{
shfEditMessageSMS.putString("SMSRESPONDERONOFF", "ON");
shfEditMessageSMS.commit();
showNotification("ON");
}
else
{
shfEditMessageSMS=shfResponderMessage.edit();
shfEditMessageSMS.putString("SMSRESPONDERONOFF", "OFF");
shfEditMessageSMS.commit();
showNotification("OFF");
String SMSResponderOnOrOff=shfResponderMessage.getString("SMSRESPONDERONOFF", "NONE");
Log.i("SMS Responder on click "+SMSResponderOnOrOff," ");
}
}
});
As you can see in the code that if toggle button in unchecked i am doing
shfEditMessageSMS.putString("SMSRESPONDERONOFF", "OFF");
shfEditMessageSMS.commit();
but when I am retrieving and printing using log
String SMSResponderOnOrOff=shfResponderMessage.getString("SMSRESPONDERONOFF", "NONE");
Log.i("SMS Responder on click "+SMSResponderOnOrOff," ");
It always shows "ON" in the logs.
What could be the problem.
thanks.
i have implement the Same thing in my application. Might Help you out to Solve your Problem.Though Could Not able to Find out the Mistake you have done in your Code. Refere below code below.
boolean on;
public SharedPreferences spref;
final String PREF_NAME="preferences";
ToggleButton tb;
#Override protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fb_intermidiate);
spref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
tb = (ToggleButton) findViewById(R.id.toggleButton1);
on = spref.getBoolean("On", true); //default is true
if (on = true)
{
tb.setChecked(true);
} else
{
tb.setChecked(false);
}
back = (Button)findViewById(R.id.button_back);
//back.setText(R.string.back_button_in_settings);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
}); }
public void onToggleClicked(View view) {
on = ((ToggleButton) view).isChecked();
if (on) {
Toast.makeText(this, "On : Notification will be Enabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("On", true); // value to store
editor.commit();
} else {
Toast.makeText(this, "Off : Notification will be Disabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor =spref.edit();
editor.putBoolean("On", false); // value to store
editor.commit();
} }
I had a similar problem but with saving a String array. I "solved" the problem by incrementing a variable on each save.
public void saveProfileList(Context context) {
SharedPreferences sharedprefs = context.getSharedPreferences(PREFS_NAME,Activity.MODE_PRIVATE);
Editor editor = sharedprefs.edit();
editor.putStringSet("vpnlist", profiles.keySet());
// For reasing I do not understand at all
// Android saves my prefs file only one time
// if I remove the debug code below :(
int counter = sharedprefs.getInt("counter", 0);
editor.putInt("counter", counter+1);
editor.apply();
}
There seems to be a bug somewhere in the android code that does not always detect the sharedpreferences as changed.
I have a vague recollection that it can take a while for the value to be read back correctly. You can solve that by encapsulating the value and store it in a variable, from where you also retrieve it. You should also consider using apply() instead of commit() since it does not interrupt the UI thread. Thus, I propose something like:
public class Preferences {
private SharedPreferences mPrefs;
private static final String KEY = "SMSRESPONDERONOFF";
private String mValue;
public Preferences(SharedPreferences prefs) {
mPrefs = prefs;
}
public String getValue() {
if (mValue == null) {
mValue = mPrefs.getString(KEY, "NONE");
}
return mValue;
}
public void setValue(String value) {
mValue = value;
mPrefs.edit().putString(KEY, value).apply();
}
}
I decided to use sharedPreferences so I could store the value of a togglebutton on my activity Preferences. On my main activity I want to hide a twitter button when the user clicks the twitter button in the Preferences activity.
private SharedPreferences prefs;
private String prefName = "MyPref";
private ToggleButton timer, twitter;
// this is the key used to set the timer to visible or hidden
private static final String TIMER_KEY = "timekey";
private static final String TWITTER_KEY= "tweet";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preferences);
timer = (ToggleButton)findViewById(R.id.timer_pref);
twitter =(ToggleButton)findViewById(R.id.twitter_pref);
timer.setChecked(true);
twitter.setChecked(true);
// Toast.makeText(Preferences.this, timer, Toast.LENGTH_SHORT).show();
Button b = (Button) findViewById(R.id.home_btn);
b.setOnClickListener(new View.OnClickListener()
{
// now add the new screen
public void onClick(View arg0) {
// TODO Auto-generated method stub
// get the shared perference data
Intent i = new Intent(Preferences.this, AndroidGUIActivity.class);
startActivity(i);
}
});
twitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
prefs = getSharedPreferences("MyPref", 0 );
SharedPreferences.Editor editor = prefs.edit();
if (timer.isChecked() == true)
{
editor.putBoolean("twitterButtonStatus", true);
}
else if(timer.isChecked() == false)
{
editor.putBoolean("twitterButtonStatus", false);
}
// now save the value that is passed to the editor.putBoolean function
// the twitter data hase been saved
editor.commit();
// now store the variable so that it can be copied to another activity
Bundle b = new Bundle();
}
});
There is no need to transfer Preferences through activities using intent.
You can access your "shared"Preferences from any activity.
You just put the button status with a string key inside:
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("twitterButtonStatus", buttonStatus);
And in another activity you retrieve these preferences using string key ("twitterButtonStatus"):
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
boolean buttonStatus = settings.getBoolean("twitterButtonStatus", false); // second param is default!
See: http://developer.android.com/guide/topics/data/data-storage.html
Edit:
Youre saving SharedPrefs now, to get them back and set your Button Gone do something like this:
SharedPreferences settings = getSharedPreferences(prefName, 0);
boolean buttonStatus = settings.getBoolean(TWITTER_KEY, true); //2nd is default
if(buttonstatus==false) twitter.setVisibility(View.GONE);
I am currently developing an android game and I have an options screen which at the moment has one Option in the form of a ToggleButton: Music on, or Music off.
I currently have this boolean in place, so the class checks if the music is currently playing and then this determines if the ToggleButton is checked or not:
private boolean isMyServiceRunning(String serviceCanonicalClassName) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceCanonicalClassName.equals(service.service.getClassName())) {
return true;
}
}
return false;
}
So now I want to be able to send the values of True or False to a SQLite database I have set up. At this current moment in time, the only way I can do this is creating a TextView which changes value whether the ToggleButton is checked or not. The value in the TextView is then sent to the database successfully, but this creates problems such as not saving the current settings selected by the user.
Thank you to anyone who replies, if you require anymore code to help you answer I will supply it asap.
I have found some of the answers to be quite confusing, so I think it would be best if I just copied all of my code to here so you can get a better understanding:
public class OptionsActivity extends Activity {
private boolean isMyServiceRunning(String serviceCanonicalClassName) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceCanonicalClassName.equals(service.service.getClassName())) {
return true;
}
}
return false;
}
Intent i; // Handles MyMusicService.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
final TextView tSound = (TextView) findViewById(R.id.textView2);
final TextView tJoin = (TextView) findViewById(R.id.textView3);
final Button saveBtn = (Button) findViewById(R.id.optSaveBtn);
final Button tblBtn = (Button) findViewById(R.id.tableBtn);
i=new Intent(this, MyMusicService.class);
final ToggleButton soundOption = (ToggleButton) findViewById(R.id.soundPref);
final ToggleButton joinOption = (ToggleButton) findViewById(R.id.joinPref);
boolean musicPlays = isMyServiceRunning(MyMusicService.class.getCanonicalName());
boolean joinChecking = joinOption.isChecked();
soundOption.setChecked(musicPlays);
if(musicPlays==true){
tSound.setText("On");
}
if(musicPlays==false) {
tSound.setText("Off");
}
if(joinChecking==true){
tJoin.setText("Auto");
}
if(joinChecking==false){
tJoin.setText("Manual");
}
soundOption.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks to control sound being on and off.
if(soundOption.isChecked()) {
Toast.makeText(OptionsActivity.this, "Music on.", Toast.LENGTH_SHORT).show();
startService(i);
}
else {
if(stopService(i)==true){
soundOption.setChecked(false);
stopService(i);
Toast.makeText(OptionsActivity.this, "Music off.", Toast.LENGTH_SHORT).show();
}
}
}});
joinOption.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(joinOption.isChecked()){
Toast.makeText(OptionsActivity.this, "Auto", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(OptionsActivity.this, "Manual", Toast.LENGTH_SHORT).show();
}
}
});
tblBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent shmoo = new Intent(OptionsActivity.this, SQLView.class);
startActivity(shmoo);
}
});
saveBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
switch (v.getId()){
case R.id.optSaveBtn: //Determine what will happen when the user presses the "Submit button".
boolean optionsWork = true;
try{
String sound = tSound.getText().toString();
String join = tJoin.getText().toString();
optionsDB entry = new optionsDB(OptionsActivity.this); //Creating a new instance of MasterMind game
entry.open();
entry.createOptionEntry(join, sound); //Passing both strings
entry.close();
}catch (Exception e){ //Creating an error message if for some reason the app cannot transfer data to the Database.
Toast.makeText(OptionsActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
finally { //Creating an AlertDialog box when the user presses the Submit button.
if (optionsWork){
Toast.makeText(OptionsActivity.this, "Settings Saved", Toast.LENGTH_SHORT).show();
}
}
break;
}
}
});
}
protected void onDestroy() {
if (this.isFinishing()){
super.onDestroy();
stopService(i);
}
}
}
SQLite doesn't handle a boolean type. I always just use smallint and put either a 1 or a 0 in the field. make sure you set it to not accept nulls, and set the default value to either 1 or 0, given your usecase.
here's an example:
CREATE TABLE "db"."boolean_example" ("boolean_example_field" smallint NOT NULL DEFAULT 0);
To store preferences better idea probably will be use Shared Preferences.
And here is example:
SharedPreferences settings = getSharedPreferences("GameSettings", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("EnableMusic", mSilentMode);
editor.commit();
...
boolean isOn = settings.getBoolean("EnableMusic",true);