Button image not changing in MainActivity.onCreate - java

I have a mute button that mutes my app via onclick. When I return to MainActivity (where the button is) I use the savedInstanceState method to keep muted or to unmute the app (depending on what was the configuration when the user exited the activity). If the button was clicked and the app is on mute I want (when I return to MainActivity) the button to be shown as muted (I have different images for mute and unmute).
My code:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.mutecounterkeydefault);
mutecounter= sharedPref.getInt(getString(R.string.mutecounterkey), defaultValue);
mutebb = (ImageButton) findViewById(R.id.muteb);
if (mutecounter == 1) {
mutebb.setImageResource(R.mipmap.muteon);} //this if is not working
mutebb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayerPool.mute = !MediaPlayerPool.mute;
if (mutecounter == 0) {
mutebb.setImageResource(R.mipmap.muteon);
mutecounter = 1;
} else {
mutebb.setImageResource(R.mipmap.muteoff);
mutecounter = 0;
}
}
});
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
editor.apply();
The solution code is
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.mutecounterkeydefault);
mutecounter= sharedPref.getInt(getString(R.string.mutecounterkey), defaultValue);
mutebb = (ImageButton) findViewById(R.id.muteb);
if (mutecounter == 1) {
mutebb.setImageResource(R.mipmap.muteon);
MediaPlayerPool.mute = true;
}
mutebb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
if (mutecounter == 0) {
mutebb.setImageResource(R.mipmap.muteon);
mutecounter = 1;
MediaPlayerPool.mute = true;
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
} else {
mutebb.setImageResource(R.mipmap.muteoff);
mutecounter = 0;
MediaPlayerPool.mute = false;
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
}
editor.apply();
}
});

The problem is that you're saving the muteCounter before the OnClickListener is called.
Your code will set the onClickListener, then immediately save the muteCounter to whatever value is held by mutecounter at that time, which in this case will be 0 every time.
What you need to do is this:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.mutecounterkeydefault);
int mutecounter = sharedPref.getInt(getString(R.string.mutecounterkey), defaultValue);
ImageButton mutebb = (ImageButton) findViewById(R.id.muteb);
if (mutecounter == 1) {
mutebb.setImageResource(R.mipmap.muteon);
}
mutebb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayerPool.mute = !MediaPlayerPool.mute;
SharedPreferences.Editor editor = sharedPref.edit();
if (mutecounter == 0) {
mutebb.setImageResource(R.mipmap.muteon);
mutecounter = 1;
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
} else {
mutebb.setImageResource(R.mipmap.muteoff);
mutecounter = 0;
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
}
editor.apply();
}
});
We're setting the value to save to SharedPreferences inside the OnClickListener here, so that it will always be set when the button is tapped.
That way the next time the view is loaded, it will have the new value in SharedPreferences. The way you have it currently, you're always saving the default value to SharedPreferences, not updating it when the button is pressed.

This happens because the code inside the onClick method is executed only when the button is clicked. and the code outside the onClick method is executed immediately when the activity is created. so the changes made by onClick method will not be reflected in sharedPreference because the code for saving data in preference is not get executed when the onClick method is called.
Solution:
Put the "saving data to SharedPreferences" logic inside the onClick method like this.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.mutecounterkeydefault);
mutecounter= sharedPref.getInt(getString(R.string.mutecounterkey), defaultValue);
mutebb = (ImageButton) findViewById(R.id.muteb);
if (mutecounter == 1) {
mutebb.setImageResource(R.mipmap.muteon);} //this if is not working
mutebb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayerPool.mute = !MediaPlayerPool.mute;
if (mutecounter == 0) {
mutebb.setImageResource(R.mipmap.muteon);
mutecounter = 1;
} else {
mutebb.setImageResource(R.mipmap.muteoff);
mutecounter = 0;
}
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.mutecounterkey), mutecounter);
editor.apply();
}
});

You can create a new class Data file like:
public class DataStoreTemporary {
////////////////////////////////// INSTANCE //////////////////////////////////
private static DataStoreTemporary instance = null;
public static DataStoreTemporary getInstance() {
if (null == instance) {
synchronized (DataStoreTemporary.class) {
if (null == instance) {
instance = new DataStoreTemporary();
}
}
}
return instance;
}
//Example//
private boolean isMute = false;
public boolean isMute() {
return isMute;
}
public void setMute(boolean mute) {
isMute = mute;
}
}
And for use in your code (in Activity):
boolean mute = DataStoreTemporary.getInstance.isMute; //get information
DaraStoreTemporary.getInstance.setMute(mute); //to save the state
If you don't close the app, this should work.

Related

Java code to show action on x amount of presses?

I have an iOS app that I worked on some time ago, and the function it uses I like, and would like to somehow get it to work on some Android code I have.
At the top of my MainActivity I have
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "nShownLobby";
on my onCreate I have
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
And I am calling this method
changeTextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
long nb_shown_lobby = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).getLong("nShownLobby", 0);
++nb_shown_lobby;
if ((nb_shown_lobby % 20) == 0) {
this.turnAround();
}
int random = (int) (Math.random() * manyDifferentStrings.length);
if (random == oldVaue) {
random = (int) (Math.random() * manyDifferentStrings.length);
}
changingText.setText(manyDifferentStrings[random]);
oldVaue = random;
try {
mySound.start();
} catch (NullPointerException e) {
mySound = MediaPlayer.create(MainActivity.this, R.raw.sound);
}
}
private void turnAround() {
//Do something here
Log.i("Do Something ", "");
}
});
The intention is that after every 20 presses, the turnAround() method is called but it does not... It just gets ignored - I am guessing I have missed something?
**According to your question your code should be like this**
private SharedPreferences sharedpreferences;
private SharedPreferences.Editor editor;
private static final String MyPREFERENCES = "nShownLobby";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
editor = sharedpreferences.edit();
changeTextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
int nb_shown_lobby = sharedpreferences.getInt("nShownLobby", 0);
if ((nb_shown_lobby % 20) == 0) {
turnAround();
}
nb_shown_lobby += 1;
editor.putInt("nShownLobby", nb_shown_lobby);
editor.commit();
int random = (int) (Math.random() * manyDifferentStrings.length);
if (random == oldVaue) {
random = (int) (Math.random() * manyDifferentStrings.length);
}
changingText.setText(manyDifferentStrings[random]);
oldVaue = random;
try {
mySound.start();
} catch (NullPointerException e) {
mySound = MediaPlayer.create(MainActivity.this, R.raw.sound);
}
}
});
}
//created this in activity, not in the button onclick
private void turnAround() {
//Do something here
Log.i("Do Something ", "");
}

Radio Button from another activity remains null?

In one activity I have my radio buttons. I'm able to save the selected state of the radio buttons throughout the application. In another activity I want to check which radio button is checked, but the radio buttons keep returning null.
Here's the first activity:
sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
go_back_btn = (Button) findViewById(R.id.go_back_btn);
distancebtn_group = findViewById(R.id.distance_btn_group);
miles_btn = (RadioButton) findViewById(R.id.miles_btn);
kilometer_btn = (RadioButton) findViewById(R.id.kilometer_btn);
go_back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(MILESBTN, miles_btn.isChecked());
editor.putBoolean(KMBTN, kilometer_btn.isChecked());
editor.apply();
Intent intent = new Intent(settings.this, home.class);
intent.putExtra(MILESBTN, miles_btn.isChecked());
intent.putExtra(KMBTN, kilometer_btn.isChecked());
startActivity(intent);
}
});
kilometer_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(KMBTN, kilometer_btn.isChecked());
editor.apply();
}
});
miles_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(MILESBTN, miles_btn.isChecked());
editor.apply();
}
});
sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
kilometer_btn.setChecked(sharedPreferences.getBoolean("kilometer_btn", true));
miles_btn.setChecked(sharedPreferences.getBoolean("miles_btn", false));
}
Here's my second activity:
distance_counter = (TextView) findViewById(R.id.distance_counter);
distancebtn_group = (RadioGroup) findViewById(R.id.distance_btn_group);
miles_btn = (RadioButton) findViewById(R.id.miles_btn);
kilometer_btn = (RadioButton) findViewById(R.id.kilometer_btn);
distancebtn_group = findViewById(R.id.distance_btn_group);
final SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(settings.GetInfo, MODE_PRIVATE);
final Boolean milesbutton = sharedPreferences.getBoolean(MILESBTN, false);
final Boolean kilometerbutton = sharedPreferences.getBoolean(KMBTN, true);
Boolean milesbtn = getIntent().getBooleanExtra(MILESBTN, false);
Boolean kilometerbtn = getIntent().getBooleanExtra(KMBTN, true);
getIntent().getBooleanExtra(MILESBTN, false);
getIntent().getBooleanExtra(KMBTN, true);
}
}
});
}
#Override
public void onLocationChanged(Location location) {
curr_location = location;
if (start_location == null) {
start_location = curr_location;
end_location = curr_location;
} else
end_location = curr_location;
ChooseMetricUnits();
distance_counter.setText(new DecimalFormat("#.##").format(distance));
current_speed = location.getSpeed() * 2.236936;
SpdInmph.setText(new DecimalFormat("0.00").format(current_speed));
current_speed = location.getSpeed() * 3.6;
SpdInkmh.setText(new DecimalFormat("0.00").format(current_speed));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private void distanceInMeters() {
distance = distance + (start_location.distanceTo(end_location));
start_location = end_location;
}
private void distanceInMiles() {
distance = distance + (start_location.distanceTo(end_location) * 0.00062137);
}
private void distanceInkilometers() {
distance = distance + (start_location.distanceTo(end_location) / 1000);
start_location = end_location;
}
public void ChooseMetricUnits() {
final SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(settings.GetInfo, MODE_PRIVATE);
Boolean milesbutton = sharedPreferences.getBoolean(MILESBTN, false);
Boolean kilometerbutton = sharedPreferences.getBoolean(KMBTN, true);
Boolean milesbtn = getIntent().getBooleanExtra(MILESBTN, true);
Boolean kilometerbtn = getIntent().getBooleanExtra(KMBTN, true);
getIntent().getBooleanExtra(MILESBTN, false);
getIntent().getBooleanExtra(KMBTN, true);
if(miles_btn.equals(milesbutton)) {
distanceInMiles();
: Run
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Object.equals(java.lang.Object)' on a null object reference
at mobile.run_interface.ChooseMetricUnits(run_interface.java:325)
enter image description here
As you can see the problem is here:
if(miles_btn.equals(milesbutton)) {
I've used BOTH putBoolean and putExtra to see if something different would happen when I pull the values from either one. Same result. I've placed the code for retrieving values, under create AND also under my ChooseMetricsUnits void method. My buttons are still null.
What am I doing wrong?
Has the activities the same layout? If they are not the same checks the import of R.id.miles_btn
And here there is another problem:
if(miles_btn.equals(milesbutton))
miles_btn is the RadioButton and milesbutton is a Boolean, so you must to change the code by:
if(miles_btn.isChecked() == milesbutton)
Solved the problem:
Hopes this helps anyone else in the future...\
private void ChooseMetricUnits() {
final SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(GetInfo, MODE_PRIVATE);
final Boolean MetricUnit = sharedPreferences.getBoolean(settings.KMBTN, true);
if(MetricUnit) {
distanceInkilometers();
} else
distanceInMiles();
}
}

I can't save integer

I Want to save the counter in my application memory and showing it.
I've tried sharedpreferences and didn't work.
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counter = counter + 1;
tvCounter.setText(String.valueOf(counter));
}
});
}
protected int Counter(View view) {
SharedPreferences settings = getSharedPreferences(String.valueOf(counter), 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("int value", counter);
editor.commit();
sharedPreferences.getInt(String.valueOf(counter), -1);
return 0;
}
}
Counter is working,but application not saving anything.
SharedPreferences save key-value pair.
editor.putInt("int value", counter);
You are saving value of counter in key "int value".
And trying to retrieve it by wrong key
sharedPreferences.getInt(String.valueOf(counter), -1);
What you should do instead is
sharedPreferences.getInt("int value", -1);
I think you are also mixing up preferences file name. To cut confusion use final String's in the class scope.
private final String prefsFileName = "counterFile"; // file name for your shared preferences.
private final String counterKey = "counter"; // key to identify counter in your preferences.
To save counter value to shared preferences create a method.
private boolean saveCounter(int counter){
SharedPreferences prefs = getSharedPreferences(prefsFileName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(counterKey, counter);
return editor.commit();
}
To get counter value from shared preferences use another method.
private int getCounterValue() {
SharedPreferences prefs = getSharedPreferences(prefsFileName, Context.MODE_PRIVATE);
return prefs.getInt(counterKey, -1);
}

Save the changed language on app with Shared Preferences

I have this code, are two buttons, one for spanish and other for english, just i use another class which is "Language Helper", to change language, and when its done i reload the activity:
btn_es.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LanguageHelper a = new LanguageHelper();
a.cambiarInt(0);
b = 0;
SharedPreferences sp = getSharedPreferences("language", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("key", b);
editor.apply();
LanguageHelper.changeLocale(getResources(), b);
finish();
startActivity(getIntent());
Animatoo.animateShrink(CMF_Settings.this);
}
});
btn_en.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LanguageHelper a = new LanguageHelper();
a.cambiarInt(1);
b = 1;
SharedPreferences sp = getSharedPreferences("language", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("key", b);
editor.apply();
LanguageHelper.changeLocale(getResources(), b);
finish();
startActivity(getIntent());
Animatoo.animateFade(CMF_Settings.this);
}
});
Two buttons change the language, and this class:
public class LanguageHelper {
int key = 0;
public static void changeLocale(Resources res, int locale) {
Configuration config = new Configuration(res.getConfiguration());
switch (locale) {
case 0:
config.locale = new Locale("es");
break;
case 1:
config.locale = Locale.ENGLISH;
break;
}
res.updateConfiguration(config, res.getDisplayMetrics());
}
public void cambiarInt(int i){
key = i;
}
}
So with that i can change the language in all aplication, but when i close and started again, i use this code to load the saved language:
public void LoadInt() {
SharedPreferences sp = getSharedPreferences("language", Activity.MODE_PRIVATE);
int b2 = sp.getInt("key", b);
if(b2==0){
LanguageHelper a = new LanguageHelper();
a.cambiarInt(0);
LanguageHelper.changeLocale(getResources(), b2);
finish();
startActivity(getIntent());
Animatoo.animateFade(Settings.this);
}else{
LanguageHelper a = new LanguageHelper();
a.cambiarInt(1);
LanguageHelper.changeLocale(getResources(), b2);
finish();
startActivity(getIntent());
Animatoo.animateFade(Settings.this);
}
}
but doesn't load. So there's another easily way to change and save? or what i need more?

sharedPreferences help. How do I save an int?

I can't for the life of me seem to figure out how to save an int. All I want to do is save leftCounter into a file and retrieve it whenever I reboot my code.
public class SalesTrack extends Activity {
byte leftCounter = 0;
byte centerCounter = 0;
byte rightCounter = 0;
int total;
int x, y, z;
public static final String PREFS = "data";
TextView counterAAL, counterUPG, counterNL, counterTotal;
private final String LEFTY = "6";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sales_track);
counterAAL = (TextView) findViewById(R.id.left_number);
counterUPG = (TextView) findViewById(R.id.center_number);
counterNL = (TextView) findViewById(R.id.right_number);
counterTotal = (TextView) findViewById(R.id.total);
SharedPreferences sharedPref = this.getSharedPreferences(LEFTY, 0);
sharedPref.getInt("data", leftCounter);
counterAAL.setText(PREFS);
}
public void LeftInc(View v) {
leftCounter++;
counterAAL.setText("" + leftCounter);
Refresh();
}
public void LeftDec(View v) {
leftCounter--;
counterAAL.setText("" + leftCounter);
Refresh();
}
public void CenterInc(View v) {
centerCounter++;
counterUPG.setText("" + centerCounter);
Refresh();
}
public void CenterDec(View v) {
centerCounter--;
counterUPG.setText("" + centerCounter);
Refresh();
}
public void RightInc(View v) {
rightCounter++;
counterNL.setText("" + rightCounter);
Refresh();
}
public void RightDec(View v) {
rightCounter--;
counterNL.setText("" + rightCounter);
Refresh();
}
// Refresh Total after every click.
public void Refresh() {
x = leftCounter * 10;
y = centerCounter * 20;
z = rightCounter * 35;
total = x + y + z;
counterTotal.setText("" + total);
SharedPreferences sharedPref = getSharedPreferences(PREFS, 0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("data", leftCounter);
editor.commit();
}
}
You have a mistake in your code.
// SharedPreferences sharedPref = getSharedPreferences(PREFS, 0); (This line is wrong)
SharedPreferences sharedPref = getSharedPreferences(LEFTY, 0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("data", leftCounter);
editor.commit();
so you get the data from the file but it's detected as String ?
you can use the parse function to convert the String into Integer
int counter = Integer.parseInt(stringvalue);
You get the preferences with two different names LEFTY and PREFS. Given the names, I think you want to change the following line in your onCreate
SharedPreferences sharedPref = this.getSharedPreferences(LEFTY, 0);
to
SharedPreferences sharedPref = this.getSharedPreferences(PREFS, 0);
SharedPreferences sharedPref = getSharedPreferences(LEFTY, 0);
SharedPreferences.Editor editor = sharedPref .edit();
editor.putInt("data", leftCounter);
editor.commit();
You are saving your data inside preference named PREFS and fetching through preference nameLEFTY
Try to change your preference name from LEFTY to PREFS under onCreate().
protected void onCreate(Bundle savedInstanceState)
{
...
SharedPreferences sharedPref = this.getSharedPreferences(PREFS, 0);
}
Change like this
SharedPreferences sharedPref = = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("data", leftCounter);
editor.commit();

Categories