cannot Handle SwitchPreference checked state through AlertDialog - android

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

Related

Multiple Check Box's Action including Don't Ask Me Again at the When I Clicked Exit Button

[Here from Dialog Box I keep 3 Check Box,One user can chose one or more that one as they want.As example if one chose clear history and dont ask me again than when i click yes button it clean all history and it never see the dialog in future.My problem is it work fine when chose only one but when chose more that one it get only 1st one .`
#Override
public void closeBrowserFromRightMenu() {
createExitDialog();
}
public void createExitDialog() {
dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
//View view = LayoutInflater.from(this).inflate(this, R.layout.alert_layout, null);
View view = View.inflate(this, R.layout.alart_exit_dialog, null);
CheckBox dontShowAgain = view.findViewById(R.id.select_3);
CheckBox clearHistory = view.findViewById(R.id.select_1);
CheckBox clearCookies = view.findViewById(R.id.cat_select_2);
//noinspection Convert2Lambda
view.findViewById(R.id.ritsDialogCancle).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
TextView title = view.findViewById(R.id.ritsDialogTitle);
title.setText(getResources().getString(R.string.exit_message));
// TextView message = view.findViewById(R.id.ritsDialogMessage);
//message.setVisibility(View.GONE);
Button confirm = view.findViewById(R.id.ritsDialogAgree);
//noinspection Convert2Lambda
confirm.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String checkBoxResult = "NOT checked";
if (clearCookies.isChecked()) {
Log.e("hgguygujgjjyfg", "clear cookies");
WebUtils.clearCookies(BrowserActivity.this);
//mMessageHandler.sendEmptyMessage(2);
}
if (clearHistory.isChecked()) {
Log.e("hgguygujgjjyfg", "clear history");
WebUtils.clearHistory(BrowserActivity.this, mHistoryDatabase);
//mMessageHandler.sendEmptyMessage(1);
}
if (dontShowAgain.isChecked()) {
checkBoxResult = "checked";
SharedPreferences settings = getSharedPreferences(SETTINGS_ASK_ME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("skipMessage", checkBoxResult);
// Commit the edits!
editor.apply();
}
dialog.dismiss();
ExitActiivity.exitApplication(BrowserActivity.this);
}
});
SharedPreferences settings = getSharedPreferences(SETTINGS_ASK_ME, 0);
String skipMessage = settings.getString("skipMessage", "NOT checked");
if (!skipMessage.equals("checked")) {
dialog.setContentView(view);
dialog.show();
} else {
ExitActiivity.exitApplication(BrowserActivity.this);
}
}
]
Here is Image Description

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);

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 save state of checkbox? if is enabled or disabled

I'm making an app that have a lot of checkbox. I wanted save the states of these but only could save if these are checked, but now I want save if is enabled or disabled, since some checkbox active states to other checkbox. How can i do that?
...
if (view.equals(contador11)){
if(contador11.isChecked()){
contador14.setEnabled(true);
}else{
contador14.setEnabled(false);
}
}
if (view.equals(contador12)){
if(contador12.isChecked()){
contador13.setEnabled(true);
contador26.setEnabled(true);
}else{
contador13.setEnabled(false);
contador26.setEnabled(false);
}
}
if (view.equals(contador7)){
if(contador7.isChecked()){
contador15.setEnabled(true);
}else{
contador15.setEnabled(false);
}
}
...
I'm not following your code exactly, but assuming you want to save all of them at the same time, you could save code by just putting them in a list or something. Here's an example.
private SharedPreferences prefs;
private CheckBox[] contadors;
private CheckBox contador1, contador2, contador3, contador4, contador5, contador6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
contador1 = (CheckBox) findViewById(R.id.contador1);
contador2 = (CheckBox) findViewById(R.id.contador2);
contador3 = (CheckBox) findViewById(R.id.contador3);
contador4 = (CheckBox) findViewById(R.id.contador4);
contador5 = (CheckBox) findViewById(R.id.contador5);
contador6 = (CheckBox) findViewById(R.id.contador6);
}
public void clickContador(View view) { // Just for testing
CheckBox contador = (CheckBox) view;
view.setEnabled(false);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveContadors();
}
#Override
protected void onResume() {
super.onPostResume();
contadors = new CheckBox[]{contador1, contador2, contador3, contador4, contador5, contador6};
loadContadors();
}
private void saveContadors() {
SharedPreferences.Editor editor = prefs.edit();
for (int i = 0; i < contadors.length; i++)
editor.putBoolean("contador" + i, contadors[i].isEnabled());
editor.apply();
}
private void loadContadors() {
for (int i = 0; i < contadors.length; i++)
contadors[i].setEnabled(prefs.getBoolean("contador" + i, true));
}
<CheckBox
android:id="#+id/contador1"
android:onClick="clickContador"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
To put the state of your CheckBox, we can use SharedPreferences:
CheckBox contador = (CheckBox) findViewById(R.id.contador1);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
if (contador.isChecked()) {
prefs.edit().putBoolean("key", true).commit(); // put true value
}else{
prefs.edit().putBoolean("key", false).commit(); // put false value
}
To get the value you saved back:
boolean myContador = prefs.getBoolean("key", false);
if (myContador == true) {
// do your thing
}else{
// the value is false, do something
}

Changing background colour with SharedPreference in 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);
}
}

Categories

Resources