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);
Related
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
I have two activities. In the second activity I have a spinner. what I would like to happen is after the user selects an item from the spinner it will save via actionbar press and on back press which will load the previous activity. Based on my research my activity is supposed to look something like the following below but it's not working what am I doing wrong??
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
getActionBar().setDisplayHomeAsUpEnabled(true);
spin = (Spinner)findViewById(R.id.editspin);
Intent i = this.getIntent();
note = new ArgueItem();
note.setKey(i.getStringExtra("key"));
note.setText(i.getStringExtra("text"));
EditText et = (EditText)findViewById(R.id.argueEdit);
et.setText(note.getText());
et.setSelection(note.getText().length());
}private boolean saveState() {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor prefEditor = prefs.edit();
int daddy = spin.getSelectedItemPosition();
prefEditor.putInt("savedValue",daddy);
prefEditor.commit();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
EditText et = (EditText)findViewById(R.id.argueEdit);
String argueText = et.getText().toString();
if(argueText.equals("")){
Toast.makeText(this, "Please Enter A New ", Toast.LENGTH_SHORT).show();
return false;
}
if (item.getItemId() == android.R.id.home) {
saveAndFinish();
}
return false;
}
#Override
public void onBackPressed() {
EditText et = (EditText)findViewById(R.id.argueEdit);
String argueText = et.getText().toString();
if(argueText.equals("")){
Toast.makeText(this, "Please Enter A New ", Toast.LENGTH_SHORT).show();
return;
}else{
saveAndFinish();
}
In your second activity, you have to override the onPause() and. Inside it write the saving process.
protected void onPause(){
super.onPause();
//Include the code which, save the data.
}
You should use a FragmentActivity and add/remove fragments within the same activity.
check these resources:
http://developer.android.com/guide/components/fragments.html
http://www.vogella.com/articles/AndroidFragments/article.html
This is how i'm initializing my spinner which is in the ActionBar. I'm not adding it as a custom view, but I'm using the drop down menu feature.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(adapter, new ActionBar.OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
//save in preferences
PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit().
putInt(SELECTED_DIARY_PREF, itemPosition).commit();
return true;
}
});
int selPosition = PreferenceManager.getDefaultSharedPreferences(this).getInt(SELECTED_DIARY_PREF, 0);
actionBar.setSelectedNavigationItem(selPosition);
What this code does is: saving the preference when an item of the menu is clicked, and restoring that preference when the activity is launched. Hope it helps.
I have a button in my menu with a “promo code” inside. I need to check if a user already clicked it so I can tell him (the next time he clicks it) “You already redeemed this promo code!” How do I do that? I need only the piece of code where I can check for button clicked.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean clicked = false;
switch (item.getItemId()) {
case R.id.getcode:
SharedPreferences pref = getSharedPreferences("promo", MODE_PRIVATE);
boolean activated = pref.getBoolean("activated", false);
if(activated == false) { Button btn = (Button) findViewById(R.id.getcode);
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage(getString(R.string.congrats) + "\n" + getString(R.string.promcd) + "\n" + "ASC2013-"+Build.ID+"-"+android.os.Build.SERIAL.charAt(3)+"-"+Build.SERIAL.charAt(6)+"-"+Build.SERIAL.charAt(9)+"-"+Build.SERIAL.charAt(12));
dlgAlert.setPositiveButton(R.string.go,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {"lorenzocascio#gmail.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.validreq)+Build.BOOTLOADER);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, getString(R.string.why) + "\n" + getString(R.string.validreq1) +"\n"+getString(R.string.dialogMSG1);
emailIntent.setType("plain/text");
startActivity(emailIntent);
}
});
dlgAlert.setCancelable(true);
dlgAlert.create().show();
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("activated", true);
editor.commit();
}
break;
}
switch (item.getItemId()) {
case R.id.settings:
Intent settings = new Intent(MainActivity.this, Settings.class);
MainActivity.this.startActivity(settings);
}
return true;
}
How about a simple boolean flag?
Set it to false in the beginning - as soon as the user clicks - set it to true.
private boolean clicked = false; // this is a member variable
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(clicked) {
Toast.makeText(getActivity(), "You already clicked!", 1000).show();
} else {
Toast.makeText(getActivity(), "You clicked for the first time!", 1000).show();
}
clicked = true;
}
}
}
Please be aware that the "clicked" boolean variable must be a member variable of your Activity, otherwise it will not be visible inside onClick(). A variable being a member variable simply means that it belongs to the class it is in, and not just occurs in a specific method. In the above code, "btn" would be a "normal" variable since it only appears inside onCreate() (a method), whereas "clicked" is declared for the Activity (the class it is in), and is therefore a member variable.
If you want to save if the user has clicked even after the app was closed and gets reopened, take a look at the SharedPreferences.
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
boolean clicked;
clicked = prefs.getBoolean("yourkey", false); // get a value, use whatever key you want
prefs.edit().putBoolean("yourkey", clicked).commit(); // save a value, use same key
You can save a flag in shared preferences if the user clicks the button. Next time, you can check in the shared preferences if there exists the flag.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences pref = getSharedPreferences("promo", MODE_PRIVATE);
boolean activated = pref.getBoolean("activated", false);
if(activated == false) { // User hasn't actived the promocode -> activate it
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("activated", true);
editor.commit();
}
}
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();
}
}