I would like to set up a toggle button for my android app, but I have to keep the button state for later use. I was trying to do it using sharedPreferences, my values return fine form the pref file, but the text of my button is the same, it wont change.
I have tested by putting the: tb.setChecked(false); on the end of my on create which changes the text from "on" to "off". But I can't get the same effect via my code.
What could be wrong?
Thanks!
main code:
public SharedPreferences spref;
final String PREF_NAME = "prefrences";
public String STATE = "state_value";
ToggleButton tb;
boolean on;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tour_detail);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
Bundle b = getIntent().getExtras();
tour = b.getParcelable(".Tour");
isMyTours = b.getBoolean("isMyTours");
isFollowed = b.getBoolean("isFollowed");
Log.i(LOGTAG, "Extra passed by notif is: " + tour);
refreshDisplay();
datasource = new ToursDataSource(this);
spref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
tb = (ToggleButton) findViewById(R.id.buttonFollow);
on = spref.getBoolean("On", true); //default is true
Log.i(LOGTAG, "VALUE for On is: " + on);
if (on = true) {
tb.setChecked(true);
} else {
tb.setChecked(false);
}
}
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();
boolean test_on = spref.getBoolean("On", true);
Log.i(LOGTAG, "VALUE for On is: " + test_on);
} 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();
boolean test_on = spref.getBoolean("On", true);
Log.i(LOGTAG, "VALUE for On is: " + test_on);
}
}
and button inside XML:
<ToggleButton
android:id="#+id/buttonFollow"
style="?android:attr/buttonStyleSmall"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#dedede"
android:textSize="12sp"
android:paddingTop="7dp"
android:paddingBottom="5dp"
android:drawableTop="#drawable/urmarire_detail_ico"
android:drawablePadding="-1sp"
android:textOn="Vibrate on"
android:textOff="Vibrate off"
android:onClick="onToggleClicked"/>
You have a bug in the condition check:
if (on = true) {
tb.setChecked(true);
} else {
tb.setChecked(false);
}
In Java, the comparison is done with == - in your code, value of on is set to true in the condition part of the if, so onCreate always sets the ToggleButton checked.
As a side note, it is a bad habit to compare a boolean to true - it is generally more readable code if you simply test if (on). However in your case this test is not even needed - you can simply replace the block with tb.setChecked(on)
Related
I'm trying to change the style of my Activity when the user clicks on a menu item.
When the user clicks on the NightMode menu item:
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.night_mode:
SharedPreferences sharedPrefStyle = getSharedPreferences(SAVE_TO, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPrefStyle.edit();
editor.putInt(SAVE_STYLE, R.style.nightMode);
editor.apply();
recreate();
Toast.makeText(this, "Night Mode is on", Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Then, in my onCreate(),
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPrefStyle = getSharedPreferences(SAVE_TO, Context.MODE_PRIVATE);
int style = sharedPrefStyle.getInt(SAVE_STYLE, 0);
Log.e("style", "oncreate saved style is " + style);
if (style != 0) {
setTheme(style);
}
setContentView(R.layout.my_activity);
// more code
}
But in my LogCat, this Log.e always outputs "oncreate saved style is 0," meaning nothing could be extracted from SharedPreferences.
The thing is, I tried extracting the style in onStop() and onResume(). Both successfully output the value of R.style.nightMode. So how come SharedPreferences does not work in onCreate()? Here is my LogCat for reference: So after recreate() is called,
E/style: onStop style: 2131755703 (this is R.style.nightMode)
E/style: onCreate style: 0
E/style: onResume style: 2131755703
Is there a better way to be setting the theme of an Activity at runtime? I have read through many other questions regarding this issue but cannot implement it myself. I am very new to Android so I apologize if this is trivial. Thanks in advance.
I have two buttons, Now how I can know the last button clicked using sharedpreference when start the activity again ?
the code:
private SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
init in onCreate:
sharedPreferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
I tried to do this but absolutely wrong way
if (sharedPreferences.getString("lamp", "on")) {
Toast.makeText(this, "onnnn", Toast.LENGTH_SHORT).show();
}
if (sharedPreferences.getString("lamp", "off")){
Toast.makeText(this, "offfff", Toast.LENGTH_SHORT).show();
}
first button
public void lampOff(View view) {
Log.d(tag, "lampOFF");
lamp_notConnected_Image.setVisibility(View.INVISIBLE);
lamp_Connected_Image.setVisibility(View.VISIBLE);
editor.putString("lamp", "off");
editor.commit();
}
seconde button:
public void lampOn(View view) {
Log.d(tag, "lampO");
lamp_notConnected_Image.setVisibility(View.VISIBLE);
lamp_Connected_Image.setVisibility(View.INVISIBLE);
editor.putString("lamp", "on");
editor.commit();
}
The problem lies in your condition if (sharedPreferences.getString("lamp", "on")), you aren't comparing this string to anything, either use
if (sharedPreferences.getString("lamp", "on").equals("on"))
or
save the value as boolean editor.putBoolean("lamp", true);, then you can compare the way you were doing: if (sharedPreferences.getString("lamp", true))
Note that here ("lamp", "on") the fist parameter is the identification, and the second is the default value, in case nothing is stored there yet.
See more in SharedPreferences
You need to check the shared preference value in onCreate method like:
if (sharedPreferences.getString("lamp", "off").equals("on")) { //assumed "off" as default
Toast.makeText(this, "onnnn", Toast.LENGTH_SHORT).show();
// on button is pressed last time
}
else{
Toast.makeText(this, "offfff", Toast.LENGTH_SHORT).show();
// off button is pressed last time or no button press so far
}
so I'm basically trying to set a BG image for activity2 with a button press in activity1.
I am using sharedpreference so the option will always stay.
The thing is, after the button press, I am saving a string to a SharedPreference:
public void onClick(View v) {
SharedPreferences.Editor background = getSharedPreferences("Background", MODE_PRIVATE).edit();
if(btn1 == v)
{
Toast.makeText(this, "btn1", Toast.LENGTH_SHORT).show();
background.putString("selectedBG", "White");
background.commit();
}
if(btn2 == v)
{
background.putString("selectedBG", "Black");
background.commit();
}
if(btn3 == v)
{
background.putString("selectedBG", "Blue");
background.commit();
}
if(btn4 == v)
{
background.putString("selectedBG", "Brown");
background.commit();
}
}
And then, in the onCreate of activity2:
SharedPreferences background = getSharedPreferences("Background", MODE_PRIVATE);
String chosenBackground = background.getString("SelectedBg", null);
Toast.makeText(this,"chosenBackground:" + chosenBackground, Toast.LENGTH_SHORT).show();
The last Toast, prints out chosenBackground:null, no matter what button I press.
What am I doing wrong?
Thank you.
SharedPreferences Ids are case sensitive
Change this:
String chosenBackground = background.getString("SelectedBg", null);
To this:
String chosenBackground = background.getString("selectedBG", null);
String chosenBackground = background.getString("selectedBG", null);
You can use defaultSharedPreferences for simply adding and changing data from any point of app:
Put any value example :
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(KEY, "value")
.apply();
Get value :
PreferenceManager.getDefaultSharedPreferences(context)
.getString(KEY, "Default value"
);
I made an app whos purpose is to download and set wallpaper in set intervals.
User can choose to do that only when connected to wifi or not.
Relevant code:
mWallpaperButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mSwitchWifi.isChecked()) {
mConnectivity = mConnectionDetector.isConnectedToWifi();
} else {
mConnectivity = mConnectionDetector.isConnectedToInternet();
}
if (mConnectivity) {
my code here
}
The code above works fine for setting the wallpaper the first time.
My problem is, I need the Service to check if the user wants to update wallpaper only over WIFI before doing so. At the moment, wallpaper is updated regardless of mSwitchWifi state. (which is bad, because it can use mobile data and user sometimes doesn't want that.)
I tried running similar Switch code in Service but I can't because it must be called in a UI Thread.
I also tried couple of workarounds and Intent.putExtra but I get exception:
NullPointerException: Attempt to invoke virtual method on a null object reference
Any idea how to check network state in service?
My service code atm:
public static class Service extends IntentService {
public Service() {
super("wallpaperchanger-download");
}
#Override
protected void onHandleIntent(Intent intent) {
if (url == null) {
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String getUrl = sharedPreferences.getString(pref_urlKey, null);
if (getUrl != null) {
url = getUrl;
}
}
wm = WallpaperManager.getInstance(this);
try {
InputStream input = new URL(url).openStream();
Log.v(TAG, url);
wm.setStream(input);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
loading = false;
Log.v(TAG, "Service Running Url " + url);
}
}
If you question is how to access the user selection inside a service/runnable/thread then you can use shared preferences to achieve this. So in your case when the user selects the choice for the first time you want to do something like this:
if(mSwitchWifi.isChecked()) { // i guess this is no wifi
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
Editor editor = sharedPeredences.edit()
editor.putBoolean("isWifi", false)
} else { // guessing this is wifi
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
Editor editor = sharedPeredences.edit()
editor.putBoolean("isWifi", true)
}
This is this code to check if it is true or false:
mWallpaperButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Boolean isWifi = isWifi()
if (!isWifi) { // i guess this is if not wifi
mConnectivity = mConnectionDetector.isConnectedToWifi();
} else if (isWifi) { // guessing this is wifi
mConnectivity = mConnectionDetector.isConnectedToInternet();
}
}
}
public Boolean isWifi() { // you can call this inside your service
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
Boolean wifiState = sharedPreferences.getBoolean("isWifi", true)
return wifiState;
}
This is just a very rough implementation to give an idea of how you can do it, you can improve this many ways. For example you could put the if statement thats inside the onClickListener in the isWifi() function and just call isWifi() inside your runnable/thread...
you can set list preferences to auto update functions based on the network ....
You can create separate class to check the connectivity and from that class you can select the preferences like auto update only on wifi or when connected to network or do not auto update ....
Quite new to coding for android but this issue has me tearing my hair out because it seems to make no sense at all...
I have an activity with four form elements in the layout: a CheckBox, two EditTexts and a Button.
When the user presses the button, it saves the content of the EditTexts as two preference values.
When the user presses the checkbox, it does the following:
If the checkbox is checked, load the preferences and store them into two variables.
Check if either of those variables contain empty strings after trimming them.
If so, show an error message, otherwise show a success message.
Essentially, the two text fields are used to set a pair of preferences which must not be empty when the checkbox is clicked.
It seems to work fine if I click the checkbox before pressing the button - error message or success message shown as appropriate.
If I press the save button and then click the checkbox, it always shows the success message regardless of the preferences.
Code follows (trimmed from the program as a whole)...
layout.xml
<CheckBox android:id="#+id/cboxActive" android:text="Click me!" android:onClick="toggleActive" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<EditText android:id="#+id/editFrom" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="phone"><requestFocus /></EditText>
<EditText android:id="#+id/editTo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="phone"></EditText>
<Button android:id="#+id/btnSave" android:onClick="savePrefs" android:text="Save" android:layout_width="120dp" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" />
</LinearLayout>
main class:
public class AutoMessengerActivity extends Activity
{
SharedPreferences settings;
CheckBox cboxActive;
EditText editFrom, editTo;
boolean active;
String from, to;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editFrom = (EditText) findViewById(R.id.editFrom);
editTo = (EditText) findViewById(R.id.editTo);
showPrefsInUI();
}
private void loadPrefs()
{
//Load preferences
settings = getPreferences(MODE_PRIVATE);
from = settings.getString("from", "");
to = settings.getString("to", "");
}
private void showPrefsInUI()
{
loadPrefs();
//Set UI elements to preference values
editFrom.setText(from);
editTo.setText(to);
}
public void savePrefs(View view)
{
SharedPreferences.Editor editor = settings.edit();
editor.putString("from", editFrom.getText().toString());
editor.putString("to", editTo.getText().toString());
editor.commit();
Toast.makeText(this, "Prefs saved!", Toast.LENGTH_SHORT).show();
}
public void toggleActive(View view)
{
if (cboxActive.isChecked())
{
loadPrefs();
//This toast is for debugging
//It shows the correct data in all circumstances...
Toast.makeText(this, "F: " + from + " T: " + to, Toast.LENGTH_SHORT).show();
//This is the part that seems to fail if you save then click checkbox
if (from.trim() == "" || to.trim() == "")
{
Toast.makeText(this, "Error - Prefs not saved", Toast.LENGTH_LONG).show();
cboxActive.setChecked(false);
}
else
{
Toast.makeText(this, "Success!", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(this, "Unchecked!", Toast.LENGTH_SHORT).show();
}
}
}
Hopefully that code gives an idea of the problem and allows it to be replicated...
Oh god, how silly of me - Urban and jcxavier hit the nail on the head... I forgot about that damn annoying quirk of Java! Changed the line to
from.trim().equals("") || to.trim().equals("")
And it works fine!
For what it's worth, that HAD actually crossed my mind briefly, but it was 2am when I tried equals and I got confused about requiring an Object as the parameter and ended up specifying null rather than "" - which didn't work...