-2

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

}

3 Answers3

0

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.

XurajB
  • 820
  • 1
  • 14
  • 29
  • when i pass the values to saveData, i first pass them through input validation do ensure that nothing is ever null. – 2JZIgnition Sep 23 '16 at 21:29
0

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/

Himmat Gill
  • 341
  • 3
  • 4
0

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);
Kevin O'Neil
  • 1,411
  • 1
  • 15
  • 15