Changing background colour with SharedPreference in Android - android

I want to change the background color of my app with a button. It should switch between two colors, for this I used SharedPreference, but >I don't know yet how to store the boolean for switching..
I got this:
public void method1(View view) {
SharedPreferences settings = getSharedPreferences(PREFS, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("modus", !modus);
editor.commit();
if (settings.getBoolean("modus", false)) {
int i = Color.GREEN;
LinearLayout layout = (LinearLayout) findViewById(R.id.mylayout);
layout.setBackgroundColor(i);
} else {
int j = Color.BLUE;
LinearLayout layout = (LinearLayout) findViewById(R.id.mylayout);
layout.setBackgroundColor(j);
}
}

To save and get boolean from prefs you can use this :
public class Settings
{
private static final String PREFS_NAME = "com.yourpackage.Settings";
private static final String MODUS = "Settings.modus";
private static final SharedPreferences prefs = App.getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
private Settings()
{
}
public static void setUseGreen(boolean useGreen)
{
Editor edit = prefs.edit();
edit.putBoolean(MODUS, useGreen);
edit.commit();
}
public static boolean useGreen()
{
return prefs.getBoolean(MODUS, false);
}
}
And then in your Activity just use this :
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.your_layout);
initModus();
}
public void initModus()
{
CheckBox modus = (CheckBox)findViewById(R.id.yourChackBoxId);
modus.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked)
{
Settings.setUseGreen(checked);
changeColor(checked);
}
});
boolean useGreen = Settings.useGreen();
modus.setChecked(useGreen);
}
private void changeColor(boolean checked)
{
LinearLayout layout = (LinearLayout) findViewById(R.id.mylayout);
if (useGreen) {
int green = Color.GREEN;
layout.setBackgroundColor(green);
} else {
int blue = Color.BLUE;
layout.setBackgroundColor(blue);
}
}

Related

Android: unable to read from sharedpreferences

So i have a slight problem. I have a feeling its something simple that i must be overlooking. In my second fragment im writing to sharedpreferences a certain number of keys and applying() afterwords. After i have finished writing my data to the sharedpreferences, i replace the current fragment(fragment#2), with the home fragment(fragment#1). Upon loading this fragment i call readPreferences(), which should read the data stored ealier and write the data to the various textviews i have on the home fragment. This does not happen. Im unsure at this time if its due to a write error or a read error. your help is as always, appreciated. Thanks.
Second Fragment
package lucaclock.moticlock;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class secondFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private TimePicker timePicker;
private int hour = 0;
private int min = 0;
private String mParam1;
private String mParam2;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor prefEditor;
public static final String alarmPreferences = "alarmPreferences";
public static final String alarmTimeKey = "alarmTimeKey";
public static final String alarmNameKey = "alarmNameKey";
public static final String alarmOccuranceKey = "alarmOccuranceKey";
public static final String alarmVolumeKey = "alarmVolumeKey";
public static final String alarmSnoozeKey = "alarmSnoozeKey";
public static final String alarmVisibleKey = "alarmVisibleKey";
public int snoozeTime;
public secondFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static secondFragment newInstance(String param1, String param2) {
secondFragment fragment = new secondFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_second, container, false);
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
final Button btnOK = (Button) view.findViewById(R.id.btnOK);
final TimePicker tp = (TimePicker) view.findViewById(R.id.timePicker);
//Stage 1 Components
final EditText edAlarmName = (EditText) view.findViewById(R.id.edAlarmName);
edAlarmName.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View view, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
edAlarmName.setText("");
}
return false;
}
});
final EditText edAlarmTime = (EditText) view.findViewById(R.id.edTime);
final EditText edOccurance = (EditText) view.findViewById(R.id.edOccurance);
edOccurance.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
dialogOccurance(view);
return true;
}
return false;
}
});
final SeekBar seekVolume = (SeekBar) view.findViewById(R.id.seekVolume);
seekVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
TextView tv = (TextView) view.findViewById(R.id.txtVolume);
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
tv.setText("How Loud?");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
// TODO Auto-generated method stub
tv.setText("Volume: " + Integer.toString(progress));
//Toast.makeText(getApplicationContext(), String.valueOf(progress), Toast.LENGTH_LONG).show();
}
});
final RadioButton rad5min = (RadioButton) view.findViewById(R.id.radSnooze5min);
final RadioButton rad10min = (RadioButton) view.findViewById(R.id.radSnooze10min);
rad5min.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(rad5min.isChecked() == true)
{
rad10min.setChecked(false);
snoozeTime = 5;
}
}
});
rad10min.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
if(rad10min.isChecked() == true)
{
rad5min.setChecked(false);
snoozeTime = 10;
}
}
});
final EditText edCustomSnooze = (EditText) view.findViewById(R.id.edSnoozeTime);
edCustomSnooze.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View view, MotionEvent motion)
{
edCustomSnooze.setText("");
if(motion.getAction() == MotionEvent.ACTION_DOWN)
{
rad5min.setChecked(false);
rad10min.setChecked(false);
snoozeTime = 0;
}
return false;
}
});
Button btnSave = (Button) view.findViewById(R.id.btnSaveAlarm);
TextView txtOccur = (TextView) view.findViewById(R.id.txtOccur);
final TextView txtVolume = (TextView) view.findViewById(R.id.txtVolume);
TextView txtSnooze = (TextView) view.findViewById(R.id.txtSnooze);
final Button btnCancel = (Button) view.findViewById(R.id.btnCancel);
btnOK.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String minString = null;
tp.setIs24HourView(false);
hour = tp.getCurrentHour();
min = tp.getCurrentMinute();
if(min < 10)
{
minString = new StringBuilder().append(Integer.toString(0)).append(min).toString();
}
else
minString = new StringBuilder().append(Integer.toString(min)).toString();
//tv.setText(formatTime(hour, minString));
//storeSetAlarmTime(formatTime(hour, minString));
setVisibleStage(0, view);
setVisibleStage(1, view);
edAlarmTime.setText(formatTime(hour, minString));
//HomeFragment hFrag = new HomeFragment();
//replaceFragment(hFrag);
}
});
btnCancel.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
HomeFragment hFrag = new HomeFragment();
replaceFragment(hFrag);
}
});
btnSave.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
edAlarmName.clearFocus();
edAlarmTime.clearFocus();
edOccurance.clearFocus();
edCustomSnooze.clearFocus();
//INPUT VALIDATION
//ALL INPUT IS OK. NO NULL VALUES ANYWHERE. PROCEED...
if(validateInput(edAlarmTime, edAlarmName, edOccurance, seekVolume, rad5min, rad10min, edCustomSnooze))
{
saveData(view, edAlarmName.getText().toString(), edAlarmTime.getText().toString(), edOccurance.getText().toString(), seekVolume.getProgress(), snoozeTime, sharedPreferences);
//dialogBuilder("Alarm Saved", "Your alarm has been saved");
}
else
dialogBuilder("Validation Error", "Fix your input and try again");
}
});
edAlarmTime.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View view, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
}
return false;
}
});
return view;
}
public void dialogBuilder(String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void dialogOccurance(final View view)
{
CharSequence colors[] = new CharSequence[] {"Once", "Daily", "Weekly"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("How often will this alarm repeat?");
builder.setItems(colors, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
TextView tv = (TextView) view.findViewById(R.id.edOccurance);
if(which == 0)
{
tv.setText("ONCE");
}
else if(which == 1)
tv.setText("DAILY");
else if(which == 2)
tv.setText("WEEKLY");
}
});
builder.show();
}
public void saveData(View view, String alarmName, String alarmTime, String occurance, int volume, int snoozeTime, SharedPreferences sharedPreferences)
{
prefEditor = sharedPreferences.edit();
prefEditor.putString(alarmTimeKey, alarmTime);
prefEditor.putString(alarmNameKey, alarmName);
prefEditor.putString(alarmOccuranceKey, occurance);
prefEditor.putInt(alarmVolumeKey, volume);
prefEditor.putInt(alarmSnoozeKey, snoozeTime);
prefEditor.putBoolean(alarmVisibleKey, true);
prefEditor.commit();
if(!sharedPreferences.getBoolean(alarmVisibleKey, true))
{
dialogBuilder("ERROR", "We tried writing the data, however we cant verify it exists");
}
else
{
dialogBuilder("Write Successfull", "true");
}
Toast.makeText(getActivity().getApplicationContext(), "Alarm Added", Toast.LENGTH_LONG).show();
HomeFragment hFrag = new HomeFragment();
replaceFragment(hFrag);
}
public void setVisibleStage(int stage, View view)
{
//Stage 0 Components
TimePicker tp = (TimePicker) view.findViewById(R.id.timePicker);
Button btnOK = (Button) view.findViewById(R.id.btnOK);
Button btnCancel = (Button) view.findViewById(R.id.btnCancel);
//Stage 1 Components
EditText edAlarmName = (EditText) view.findViewById(R.id.edAlarmName);
EditText edAlarmTime = (EditText) view.findViewById(R.id.edTime);
EditText edOccurance = (EditText) view.findViewById(R.id.edOccurance);
SeekBar seekVolume = (SeekBar) view.findViewById(R.id.seekVolume);
RadioButton rad5min = (RadioButton) view.findViewById(R.id.radSnooze5min);
RadioButton rad10min = (RadioButton) view.findViewById(R.id.radSnooze10min);
EditText edCustomSnooze = (EditText) view.findViewById(R.id.edSnoozeTime);
Button btnSave = (Button) view.findViewById(R.id.btnSaveAlarm);
TextView txtOccur = (TextView) view.findViewById(R.id.txtOccur);
TextView txtVolume = (TextView) view.findViewById(R.id.txtVolume);
TextView txtSnooze = (TextView) view.findViewById(R.id.txtSnooze);
if(stage == 0)
{
//STAGE 0 = ANALOG CLOCK DISPLAY ONLY
tp.setVisibility(view.INVISIBLE);
btnOK.setVisibility(view.INVISIBLE);
btnCancel.setVisibility(view.INVISIBLE);
}
else if(stage == 1)
{
//STAGE 1 = EVERYTHING ELSE VISIBLE
edAlarmName.setVisibility(view.VISIBLE);
edAlarmTime.setVisibility(view.VISIBLE);
txtOccur.setVisibility(view.VISIBLE);
edOccurance.setVisibility(view.VISIBLE);
txtVolume.setVisibility(view.VISIBLE);
seekVolume.setVisibility(view.VISIBLE);
txtSnooze.setVisibility(view.VISIBLE);
rad5min.setVisibility(view.VISIBLE);
rad10min.setVisibility(view.VISIBLE);
edCustomSnooze.setVisibility(view.VISIBLE);
btnSave.setVisibility(view.VISIBLE);
}
}
public void replaceFragment(Fragment fragment)
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, fragment);
//fragmentTransaction.addToBackStack(fragment.toString());
fragmentTransaction.commit();
}
public boolean validateInput(EditText edAlarmTime, EditText edAlarmName, EditText edOccurance, SeekBar seekVolume, RadioButton rad5min, RadioButton rad10min, EditText customSnooze)
{
String alarmTimeOK = edAlarmTime.getText().toString();
String alarmNameOK = edAlarmName.getText().toString();
String OccuranceOK = edOccurance.getText().toString();
int volumeOK = seekVolume.getProgress();
boolean FiveMinChecked = rad5min.isChecked();
boolean TenMinChecked = rad10min.isChecked();
String customSnoozeOK = customSnooze.getText().toString();
if(alarmTimeOK.matches("") || !alarmTimeOK.contains(":"))
return false;
else if(alarmNameOK.matches("") || alarmNameOK.contains("Alarm Name"))
return false;
else if(OccuranceOK.matches("") || OccuranceOK.contains("Choose Occurance"))
return false;
else if(volumeOK == 0)
return false;
else if(FiveMinChecked && customSnoozeOK.matches("Enter your own"))
return true;
else if(TenMinChecked && customSnoozeOK.matches("Enter your own"))
return true;
else if(FiveMinChecked == false && customSnoozeOK.matches("Enter your own"))
return false;
else if(TenMinChecked == false && customSnoozeOK.matches("Enter your own"))
return false;
else
return true;
}
public String formatTime(int hour, String minString)
{
String formattedString = null;
if(hour > 12)
{
formattedString = new StringBuilder().append(Integer.toString(hour - 12)).append(":").append(minString).append("PM").toString();
}
else
formattedString = new StringBuilder().append(Integer.toString(hour)).append(":").append(minString).append("AM").toString();
return formattedString;
}
}
Home Fragment
public class HomeFragment extends Fragment{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private boolean alarm1Active = false;
//private boolean alarm1Visible = false;
//public String alarm1Name;
//public String alarm1Time;
//public String alarm1Occurance;
//public int alarm1Snooze;
//public int alarm1Volume;
//public boolean fragmentSwitch;
SharedPreferences sharedPreferences;
SharedPreferences.Editor prefEditor;
public static final String alarmPreferences = "alarmPreferences";
public static final String alarmTimeKey = "alarmTimeKey";
public static final String alarmNameKey = "alarmNameKey";
public static final String alarmOccuranceKey = "alarmOccuranceKey";
public static final String alarmVolumeKey = "alarmVolumeKey";
public static final String alarmSnoozeKey = "alarmSnoozeKey";
public static final String alarmVisibleKey = "alarmVisibleKey";
public boolean devMode = true;
public HomeFragment() {
// Required empty public constructor
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
final View view = inflater.inflate(R.layout.fragment_home, container, false);
//CODE HERE
readPreferences(view);
FloatingActionButton fabAddAlarm = (FloatingActionButton) view.findViewById(R.id.fabRefresh);
fabAddAlarm.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getActivity().getApplicationContext(), "Reading Preferences", Toast.LENGTH_LONG).show();
readPreferences(view);
}
});
return view;
}
public void readPreferences(View view)
{
TextView tvAlarm1Name = (TextView) view.findViewById(R.id.tvAlarm1Name);
TextView tvAlarm1Time = (TextView) view.findViewById(R.id.tvAlarm1Time);
TextView tvAlarm1Occurance = (TextView) view.findViewById(R.id.tvAlarm1Occurance);
Switch swAlarm1Active = (Switch) view.findViewById(R.id.swEnableAlarm1);
Button btnEditAlarm1 = (Button) view.findViewById(R.id.btnEditAlarm1);
TextView status = (TextView) view.findViewById(R.id.tvNoAlarms);
sharedPreferences = getActivity().getSharedPreferences(alarmPreferences, Context.MODE_PRIVATE);
String alarm1Name = sharedPreferences.getString(alarmNameKey, null);
String alarm1Time = sharedPreferences.getString(alarmTimeKey, null);
String alarm1Occurance = sharedPreferences.getString(alarmOccuranceKey, null);
int alarm1Snooze = sharedPreferences.getInt(alarmSnoozeKey, 0);
int alarm1Volume = sharedPreferences.getInt(alarmVolumeKey, 0);
boolean alarm1Visible = sharedPreferences.getBoolean(alarmVisibleKey, false);
if(!alarm1Visible)
{
status.setVisibility(View.VISIBLE);
status.setText("You have no alarms set!");
}
else if(alarm1Visible)
{
status.setVisibility(View.INVISIBLE);
tvAlarm1Time.setVisibility(View.VISIBLE);
tvAlarm1Name.setVisibility(View.VISIBLE);
tvAlarm1Occurance.setVisibility(View.VISIBLE);
btnEditAlarm1.setVisibility(View.VISIBLE);
swAlarm1Active.setVisibility(View.VISIBLE);
tvAlarm1Time.setText(alarm1Time);
tvAlarm1Name.setText(alarm1Name);
tvAlarm1Occurance.setText(alarm1Occurance);
}
}
}
While saving string on SharedPreferences make sure that you are not saving null. It will instead clear the preference key.
prefEditor.putString(alarmOccuranceKey, occurance);
Make sure that occurance is not null.
Please use commit() to save the data. Also you can create a simple reusable class for SharedPreferences. Please refer to my customized class for the same: https://codebegetter.wordpress.com/2016/08/04/shared-preferences-reusable-class/
Based on the comments in one of the answers it looks like you have applied a solution. However, based on the code you posted here was the issue:
You are not storing and retrieving values from the same SharedPreferences file. When you store values you are using a custom named SharedPreferences file. When you try to retrieve those values you are referencing the SharedPreferences file that is specific to the Activity which hosts your secondFragment. (Which, in a way, is actually custom named as well...the framework bases it on your Activity name).
When you write values to SharedPreferences in your secondFragment you call:
sharedPreferences = getActivity().getSharedPreferences(alarmPreferences, Context.MODE_PRIVATE);
//...
prefEditor = sharedPreferences.edit();
When you attempt to read those values in your HomeFragment you call:
sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
These two code snippets don't reference the same SharePreferences file. The most direct solution would be to update the code in your HomeFragment so that you obtain the same SharePreferences file where you stored your values like so:
sharedPreferences = getActivity().getSharedPreferences(alarmPreferences, Context.MODE_PRIVATE);

cannot Handle SwitchPreference checked state through AlertDialog

Hello i am building a preference activity in which i have a SwitchPreference through i enable some EditTexts. When the switch is checked an AlertDialog for the user to pick a master password. I want if the user does not select a password the switch to be disabled again.
Code:
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment implements View.OnClickListener {
private AlertDialog pinDialog;
private SwitchPreference master;
private boolean updated;
private SharedPreferences mUpdated;
private SharedPreferences.Editor mEditor;
private Button one, two, three, four, five, six, seven, eight, nine, zero, buttonClicked, openButton, settings;
private ImageView image1, image2, image3, image4;
private TextView tv;
private AlertDialog.Builder builder;
private StringBuffer pinCode, checkPinCode;
private int count = 0;
private String encryptedString;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
master = (SwitchPreference) findPreference("master_switch");
mUpdated = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
updated = mUpdated.getBoolean("master_switch", false);
pinDialog = enablePinDialog();
pinCode = new StringBuffer();
checkPinCode = new StringBuffer();
setListeners();
bindPreferenceSummaryToValue(findPreference("coffees_file"));
bindPreferenceSummaryToValue(findPreference("snacks_file"));
bindPreferenceSummaryToValue(findPreference("sweets_file"));
bindPreferenceSummaryToValue(findPreference("spirits_file"));
bindPreferenceSummaryToValue(findPreference("beverages_file"));
bindPreferenceSummaryToValue(findPreference("beers_file"));
master.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean switched = ((SwitchPreference) preference).isChecked();
updated = !switched;
mEditor = mUpdated.edit();
mEditor.putBoolean("master_switch", updated);
mEditor.apply();
master.setSummary(!updated ? "Disabled" : "Enabled");
if (updated) {
if (pinDialog != null) {
pinDialog.show();
}
} else {
removePrefs();
}
return true;
}
});
}
private void setListeners() {
one.setOnClickListener(this);
two.setOnClickListener(this);
three.setOnClickListener(this);
four.setOnClickListener(this);
five.setOnClickListener(this);
six.setOnClickListener(this);
seven.setOnClickListener(this);
eight.setOnClickListener(this);
nine.setOnClickListener(this);
zero.setOnClickListener(this);
}
public AlertDialog enablePinDialog() {
builder = new AlertDialog.Builder(getActivity());
View view = LayoutInflater.from(builder.getContext()).inflate(R.layout.dialog_layout, null, false);
one = (Button) view.findViewById(R.id.button);
two = (Button) view.findViewById(R.id.button2);
three = (Button) view.findViewById(R.id.button3);
four = (Button) view.findViewById(R.id.button4);
five = (Button) view.findViewById(R.id.button5);
six = (Button) view.findViewById(R.id.button6);
seven = (Button) view.findViewById(R.id.button7);
eight = (Button) view.findViewById(R.id.button8);
nine = (Button) view.findViewById(R.id.button9);
zero = (Button) view.findViewById(R.id.buttonzero);
image1 = (ImageView) view.findViewById(R.id.imageView);
image2 = (ImageView) view.findViewById(R.id.imageView2);
image3 = (ImageView) view.findViewById(R.id.imageView3);
image4 = (ImageView) view.findViewById(R.id.imageView4);
tv = (TextView) view.findViewById(R.id.changeText);
builder.setView(view);
builder.setTitle("Master Password");
return builder.create();
}
private void savePassword() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(checkPinCode.toString().getBytes());
encryptedString = new String(messageDigest.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
editor.putString("master_pin", encryptedString);
editor.apply();
}
private void removePrefs() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
editor.remove("master_pin");
editor.apply();
}
private void typePassword() {
count++;
pinCode.append(String.valueOf(buttonClicked.getText()));
if (count == 1) {
image1.setImageResource(R.drawable.ic_lens_black_24dp);
} else if (count == 2) {
image2.setImageResource(R.drawable.ic_lens_black_24dp);
} else if (count == 3) {
image3.setImageResource(R.drawable.ic_lens_black_24dp);
} else if (count == 4) {
image4.setImageResource(R.drawable.ic_lens_black_24dp);
image1.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
image2.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
image3.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
image4.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
tv.setText(R.string.second_text);
}
}
private void retypePassword() {
checkPinCode.append(String.valueOf(buttonClicked.getText()));
if (count == 5) {
image1.setImageResource(R.drawable.ic_lens_black_24dp);
} else if (count == 6) {
image2.setImageResource(R.drawable.ic_lens_black_24dp);
} else if (count == 7) {
image3.setImageResource(R.drawable.ic_lens_black_24dp);
} else if (count == 8) {
image4.setImageResource(R.drawable.ic_lens_black_24dp);
checkPinCode = checkPinCode.delete(0, 4);
pinCode = pinCode.delete(4, 8);
Log.e("1st Try", pinCode.toString());
Log.e("2nd Try", checkPinCode.toString());
if (checkPinCode.toString().equals(pinCode.toString())) {
tv.setText(R.string.second_text);
Toast.makeText(getActivity(), "Master Password created", Toast.LENGTH_SHORT).show();
savePassword();
pinDialog.dismiss();
} else {
tv.setText(R.string.first_text);
Toast.makeText(getActivity(), "Pins don't match", Toast.LENGTH_SHORT).show();
count = 0;
image1.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
image2.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
image3.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
image4.setImageResource(R.drawable.ic_radio_button_unchecked_black_24dp);
pinCode.delete(0, pinCode.length());
checkPinCode.delete(0, checkPinCode.length());
pinDialog.dismiss();
}
}
}
Edit: using Ajit Pratap Singh answer
master.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
final boolean switched = ((SwitchPreference) preference).isChecked();
updated = !switched;
mEditor = mUpdated.edit();
mEditor.putBoolean("master_switch", updated);
Log.e("Switch is", String.valueOf(updated));
mEditor.apply();
master.setSummary(!updated ? "Disabled" : "Enabled");
if (updated) {
if (pinDialog != null) {
pinDialog.show();
}
} else {
removePrefs();
}
pinDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
updated = switched;
mEditor = mUpdated.edit();
mEditor.putBoolean("master_switch", updated);
Log.e("Switch after dismiss", String.valueOf(updated));
mEditor.apply();
master.setSummary(!updated ? "Disabled" : "Enabled");
}
});
return true;
}
});
The result is that the switch becomes disabled but the indicator is on:
After edit
When i dismiss it through back dialog it gets disabled but when i create the master password it still remains disabled. this happens due to master.setChecked(false); this line. if i remove it still remains enabled when i dismiss it.
You need to use Dismiss Listener
http://developer.android.com/reference/android/content/DialogInterface.OnDismissListener.html

Using Shared preferences to remember the font size that a user prefers in Android

I'm developing a mobile songbook android application. I have enabled text to be zoomed in or out. I want the application to be able to remember the specific font size that a user prefers when a user closes a specific song to another or even better even when a user closes the application and opens it again. Here is how i tried doing it:
public void saveFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putFloat("fontsize",factor.getInt());
editor.apply();
}
public void rememberFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
double factor = sharedPref.getString("fontsize","");
factor.setInt();
}
Here is the entire class:
public class SongbookActivity extends AppCompatActivity {
private TextView wordMeaning;
private TextToSpeech convertToSpeech;
ScaleGestureDetector scaleGestureDetector;
public double factor;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dictionary);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarSongActivity);
TextView textViewTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
int dictionaryId = bundle.getInt("SONG._ID");
int id = dictionaryId + 1;
wordMeaning = (TextView)findViewById(R.id.dictionary);
String title = bundle.getString("SONG._TITLE");
String description = bundle.getString("SONG._LYRICS");
final android.support.v7.app.ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.left);
ab.setTitle(null);
ab.setDisplayHomeAsUpEnabled(true);
textViewTitle.setText(title);
textViewTitle.setSelected(true);
// textViewTitle.setMovementMethod(new ScrollingMovementMethod());
wordMeaning.setTextIsSelectable(true);
registerForContextMenu(wordMeaning);
wordMeaning.setMovementMethod(new ScrollingMovementMethod());
wordMeaning.setText(description);
scaleGestureDetector = new ScaleGestureDetector(this, new simpleOnScaleGestureListener());
}
//copy text or select
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
//user has long pressed your TextView
menu.add(0, v.getId(), 0, "Song copied to Clipboard");
//cast the received View to TextView so that you can get its text
TextView yourTextView = (TextView) v;
//place your TextView's text in clipboard
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(yourTextView.getText());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getPointerCount() > 1) {
scaleGestureDetector.onTouchEvent(event);
return true;
}
return false;
}
public void saveFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putFloat("fontsize",factor.getInt());
editor.apply();
}
public void rememberFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
double factor = sharedPref.getString("fontsize","");
factor.setInt();
}
public class simpleOnScaleGestureListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
// TODO Auto-generated method stub
float size = wordMeaning.getTextSize();
Log.d("TextSizeStart", String.valueOf(size));
float factor = detector.getScaleFactor();
Log.d("Factor", String.valueOf(factor));
float product = size*factor;
Log.d("TextSize", String.valueOf(product));
wordMeaning.setTextSize(TypedValue.COMPLEX_UNIT_PX, product);
size = wordMeaning.getTextSize();
Log.d("TextSizeEnd", String.valueOf(size));
return true;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
double factor = 1;
float size = wordMeaning.getTextSize();
saveFont(View view);
rememberFont(View view);
Log.d("TextSizeStart", String.valueOf(size));
switch (item.getItemId()) {
case R.id.small_layout:
factor = 0.5;
break;
case R.id.medium_layout:
factor = 0.9;
break;
case R.id.large_layout:
factor = 1.3;
break;
case R.id.xlarge_layout:
factor = 1.8;
break;
}
Log.d("Factor", String.valueOf(factor));
double product = size*factor;
Log.d("TextSize", String.valueOf(product));
wordMeaning.setTextSize(TypedValue.COMPLEX_UNIT_PX, (float)product);
size = wordMeaning.getTextSize();
Log.d("TextSizeEnd", String.valueOf(size));
return super.onOptionsItemSelected(item);
}
}
I'm getting errors when trying to call the method and on the method declaration. i'm a noob at this so please give me all the details you might think can help me, no matter how insignificant it can be.
here you will get all http://developer.android.com/training/basics/data-storage/shared-preferences.html
actually you storing in float with int and trying to get in string so try below
public void saveFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("fontsize",factor.getInt());
editor.commit();
}
and from getting back
public void rememberFont(View view){
SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
int prevFont = sharedPref.getInt("fontsize",-1);
}
in -1 you can set your default font
If you are having trouble with SharedPreferences, try using this. This greatly simplifies the whole process and uses SharedPreferences internally. All you have to do is copy the source file in your project and use it.
Here is an example:
In your activity's onCreate() method, initialize TinyDB.
TinyDB tinyDB = new TinyDB(this);
Then use it like this:
tinyDB.putString("fontSize", "12");
String fontSize = tinyDB.getString("fontSize");
As simple as that. There are many methods which are very useful in day to day development, just go through the source file once. Hope it helps.
Just a "light" how you can do this.
public void setVariable(float myFloat) {
pref = _context.getSharedPreferences("fontsize", Context.MODE_PRIVATE);
editor = pref.edit();
editor.putFloat("fontsize", myFloat);
editor.commit();
}
public float getVariable() {
pref = _context.getSharedPreferences("fontsize", Context.MODE_PRIVATE);
return pref.getFloat("fontsize", 5.5/*a default value*/);
}
_context can be an attribute.
EDIT1: This class works FINE for me to any 'save' issues. Change this as your need
public class SharedPreferencesManager {
// Shared Preferences
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private Context _context;
// Shared pref mode
private final int PRIVATE_MODE_SHARED_PREF = 0;
// Shared preferences file name
private final String PREF_NAME = "blabla";
/*KEYS para o sharedpreferences*/
private final String KEY_TO_USE = PREF_NAME + "setFont";
public SharedPreferencesManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE_SHARED_PREF);
editor = pref.edit();
}
public void setFont(float keySize) {
editor.putFloat(KEY_TO_USE, keySize);
editor.commit();
}
public boolean getFont() {
return pref.getFloat(KEY_TO_USE, 15/*your default value is in here (in sp)*/);
}
}
To use this, just create an object (passing the context[the activity]) and use the method GET in EVERY call/inflate of your EditText/TextView, and set the size like this
myTextView.setTextSize(mSharedPreferencesManagerObject.getVariable())
And to all of this make sense, on EVERY zoom changes, you need to call
mSharedPreference.setVariable(sizeHere)
It HAS to work. If not, the problem is in your "OnZoomChange" logic/semantic.

Android Landscape Orientation on Fragment Resetting Shared Preferences

I am using shared preferences to keep track of a Admin code that is saved on the device, I have noticed that when I go this particular fragment that has a landscape orientation the preference gets called twice and on the second time it resets to its initial null value. this is the only fragment it happens on and i have been able to narrow it down to the line
activity.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
is there a particular correct method to have shared preferences working with a landscape orientation
Here is the Code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final Activity activity = getActivity();
SharedPreferences sharedpreferences = activity.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Boolean Admin_Mode = sharedpreferences.getBoolean("AdminCode", false);
String IPaddress = sharedpreferences.getString("IP Address", "");
System.out.println(IPaddress);
System.out.println(Admin_Mode);
View rootView = inflater.inflate(R.layout.augmented_reality_view, container, false);
ActionBar actionBar = ((ActionBarActivity)activity).getSupportActionBar();
actionBar.hide();
System.out.println("here");
activity.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
mSensorManager = (SensorManager)getActivity().getSystemService(Context.SENSOR_SERVICE);
mRotationVectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
mMagneticSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.registerListener(this, mRotationVectorSensor, 10000);
mSensorManager.registerListener(this, mMagneticSensor, 10000);
HeadTracker = (ToggleButton) rootView.findViewById(R.id.HeadTracker);
return rootView;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (HeadTracker.isChecked() == true) {
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
SensorManager.getRotationMatrixFromVector(
mRotationMatrix, event.values);
if (mRotationMatrix[2] >= 0.6 && mRotationMatrix[0] >= -0.1 && mRotationMatrix[0] <= 0.2){
Left = true;
Right = false;
}
else if (mRotationMatrix[2] <= -0.8 && mRotationMatrix[0] >= -0.1 && mRotationMatrix[0] <= 0.2){
Left = false;
Right = true;
}
else{
Left = false;
Right = false;;
}
}
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
if(event.values[2] >= 390){
MagnetButtonPressed = true;
}
else{
MagnetButtonPressed = false;
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onPause()
{
super.onPause();
mSensorManager.unregisterListener(this);
}
Any Advice would be Epic :)
Cheers
Steve
///...... EDIT .........\\\
added in settings fragment code
public class Settings extends PreferenceFragment {
public SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
String IPaddress;
int PortNumber;
Boolean Admin_Mode;
public Settings() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.settings, container, false);
getActivity().setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final SharedPreferences sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
IPaddress = sharedpreferences.getString("IP Address","");
PortNumber = sharedpreferences.getInt("Port Numner", 1);
Admin_Mode = sharedpreferences.getBoolean("AdminCode", false);
final EditText mEdit = (EditText)rootView.findViewById(R.id.ipaddress);
final EditText mEdit2 = (EditText)rootView.findViewById(R.id.portnumber);
final EditText AdminCommandBox = (EditText)rootView.findViewById(R.id.AdminCommandBox);
mEdit.setText(IPaddress);
String strI = Integer.toString(PortNumber);
mEdit2.setText(strI);
Button clickButton = (Button) rootView.findViewById(R.id.Update_Settings);
clickButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("IP Address", mEdit.getText().toString());
editor.putInt("Port Numner", Integer.parseInt(mEdit2.getText().toString()));
editor.commit();
Toast.makeText(getActivity(),"Port and Ip Updated!",Toast.LENGTH_SHORT).show();
}
});
final Button Authorise = (Button) rootView.findViewById(R.id.Authorise_Button);
if (Admin_Mode == false){Authorise.setText("Authorise");}
else if (Admin_Mode == true){Authorise.setText("Deactivate");}
Authorise.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Admin_Mode == false){
if (AdminCommandBox.getText().toString().equals("FerasQUT123")) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("AdminCode", true);
editor.commit();
Toast.makeText(getActivity(),"Code Authorised",Toast.LENGTH_SHORT).show();
Authorise.setText("Deactivate");
}
else{
Toast.makeText(getActivity(),"Please Enter the Correct Code",Toast.LENGTH_SHORT).show();
}
}
else if (Admin_Mode == true){
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("AdminCode", false);
editor.commit();
Toast.makeText(getActivity()," Deactivated",Toast.LENGTH_SHORT).show();
Authorise.setText("Authorise");
}
}
});
return rootView;
}
public void onDestroy() {
super.onDestroy();
}}
In the shared preference i get the state of the admin mode at the beginning of the on create, i set it in the main activity to false and then update it in the settings fragment if the correct code is entered.
Your issue is that you are setting admin mode to false in the activity's onCreate method. When the screen orientation changes, the activity will be destroyed and recreated--so onCreate will be called again, which is setting your admin mode preference to false.

How to set a default value to SharedPreferences programmatically?

I am using SharedPreferences to keep the information about user's weight, which I need in my application. The problem is, how to set a default value (eg. 75 kg) automatically after installation? I know how to do it via .xml, but how to do this programmatically?
My code:
public class SettingsDialogFragment extends DialogFragment{
public static final String PREFS_NAME = "settings";
public Dialog onCreateDialog(Bundle savedInstanceState) {
builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Data.weight = weight;
SharedPreferences prefs = getActivity().getSharedPreferences(PREFS_NAME, 0);
Editor editor = prefs.edit();
editor.putInt("key_weight", weight);
editor.commit();
Data.ifMale = ifMale;
checkedRadio = rg.getCheckedRadioButtonId();
System.out.println("numer radio" +checkedRadio);
}
});
return builder.create();
}
}
Try this way, please.
SharedPreferences prefs = getActivity().getSharedPreferences(
PREFS_NAME, 0);
if (prefs.getInt("key_weight", null) == null) {
Editor editor = prefs.edit();
editor.putInt("key_weight", 75);
editor.commit();
}
For first time use this, or else use your code only(means without if condition).
getInt takes a default value.
prefs.getInt("key_weight", 75)
Or in a more mainstream style....
public class AppPreferences {
private SharedPreferences mPreferences;
Public AppPreferences(SharedPreferences preferences)
{
this.mPreferences = preferences;
}
private static final String KEY_WEIGHT_KEY = "key_weight";
private static final int DEFAULT_KEY_WEIGHT = 75;
public static int getKeyWeight()
{
return mPreferences.getInt(KEY_WEIGHT_KEY,DEFAULT_KEY_WEIGHT);
}
}

Categories

Resources