2

I am working on an android project where I have a scenario such as :

Task 1:

I have to get the user activity count "when ever the user starts the activity a count has to be made and stored in shared preference. (completed successfully)

Task 2:

I have to clear the user shared preference on daily basis for example ( if the user is using the app on 13-08-2017 and have count around 20 (this means he has opened the app for 20 times). For the next day that is on 14-08-2017 I want the shared preference value to be cleared in the editor.

I am unable to do the second task. How can I compare the previous and today date and clear the shared preference editor?

Below is my code where I am getting count and current date successfully :

public class Fragment_Greetings extends Fragment
{
    private SharedPreferences prefs;
    private SharedPreferences.Editor editor;
    private int totalCount;
    Date currentDate;
    String dateValue;
    public Fragment_Greetings()
    {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        View rootView= inflater.inflate(R.layout.fragment_greetings, container, false);

        // code for getting user daily basis count

        // getting the current date
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE,0);
        SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
        String curentDate = df.format(c.getTime());

        // setting up the editor
        prefs = getActivity().getPreferences(getActivity().MODE_PRIVATE);
        editor = prefs.edit();


        totalCount = prefs.getInt("counter", 0);
        totalCount++;
        editor.putInt("counter", totalCount);

        editor.commit();
        //System.out.println("Total Application counter Reach to :"+totalCount);

        Toast.makeText(getActivity(), "Hello user , you have entered into the app for "+totalCount+" th time on "+curentDate, Toast.LENGTH_SHORT).show();
        return rootView;
    }

}
Shreyash S Sarnayak
  • 2,309
  • 19
  • 23
Divakar R
  • 773
  • 1
  • 8
  • 36
  • While storing the counter in preference you can store as 'date'-"counter" instead of simple "counter" so that you can get the each day counter. One more thing instead of using shareprefernece you can try to DB also. – Muthukrishnan Rajendran Aug 13 '17 at 10:02
  • Store the date when you enter the app in shared preferences and check that stored date with the current date. If it's lesser than 1day then don't update your sharedpreferences date. Else update it. – Aditya Srivastava Aug 13 '17 at 10:03

0 Answers0