DMur
DMur

Reputation: 661

SharedPreferences keep being deleted before use

This is a doosie. I am storing int values in my shared prefs, essentially caching them so I can put them into the DB on next startup. I have a method to save them to a DB on startup.

This is followed by a method to remove the values from the shared prefs to reset them.

But they appear to keep removing before I can store them to the DB. Its like deleteMetrics(); is running before setMetrics(); no matter what I do.

Nothing works. The values are being deleted before the setMetrics(); method stores them to the DB.

If I comment out deleteMetrics(); the DB values are stored fine, but they are increasing exponentially because the sharedPrefs are not reset for each app use.

Launch activity onCreate:

Activity_Splash.this.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        setMetrics();
        deleteMetrics();
    }
});

setMetrics(); and deleteMetrics();

private void setMetrics() {
    SharedPreferences sharedPreferences = Activity_Splash.this.getSharedPreferences("com.dmurphy.remotescrumpoker", Context.MODE_PRIVATE);
    //Check if device has a network connection
    boolean connectionExists = new NetworkConnection().haveNetworkConnection(passedActivity, TAG);

    //If device has a network connection continue
    if (connectionExists) {
        Log.i(" => ", "Test1");
        try {
            String userId = mAuth.getCurrentUser().getUid();
            int teamCreated2 = sharedPreferences.getInt("teamCreatedForMetrics", 0);
            Log.i(" => ", "Test2 " + teamCreated2);
            callMetrics.startupUpdateMetrics(userId, context);
        } catch (Exception e) {
            Log.e(TAG + "onCreate", "Error setting metrics");
        }
    }
}

private void deleteMetrics() {
    SharedPreferences sharedPreferences = Activity_Splash.this.getSharedPreferences("com.dmurphy.remotescrumpoker", Context.MODE_PRIVATE);
        try {
            sharedPreferences.edit().remove("acceptedForMetrics").commit();
            sharedPreferences.edit().remove("rejectedForMetrics").commit();
            sharedPreferences.edit().remove("requestedForMetrics").commit();
            sharedPreferences.edit().remove("sm2AppointedForMetrics").commit();
            sharedPreferences.edit().remove("teamCreatedForMetrics").commit();
            sharedPreferences.edit().remove("teamDeletedForMetrics").commit();
            sharedPreferences.edit().remove("noOfPlayersForMetrics").commit();
            sharedPreferences.edit().remove("teamsMemberLeaveForMetrics").commit();
        } catch (Exception e) {
            Log.e(TAG + "onCreate", "Error setting metrics");
        }
    }

callMetrics being called by the setMetrics method:

public void startupUpdateMetrics(String userId, Context context) {
    SharedPreferences sharedPreferences = context.getSharedPreferences("com.dmurphy.remotescrumpoker", Context.MODE_PRIVATE);

    db.collection("userteammetrics").document(userId).collection("teammetrics").document("generalteammetrics").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                int teamCreated4 = sharedPreferences.getInt("teamCreatedForMetrics",0);
                Log.i(" => ", "Test4 " + teamCreated4);
                DocumentSnapshot document = task.getResult();

                if (document.exists()) {
                    int teamCreated5 = sharedPreferences.getInt("teamCreatedForMetrics",0);
                    Log.i(" => ", "Test5 " + teamCreated5);
                    int oldAccepted = Integer.parseInt(document.get("accepted").toString());
                    int oldRejected = Integer.parseInt(document.get("rejected").toString());
                    int oldRequested = Integer.parseInt(document.get("requested").toString());
                    int oldsm2Appointed = Integer.parseInt(document.get("scrummaster2sappointed").toString());
                    int oldTeamsCreated = Integer.parseInt(document.get("teamscreated").toString());
                    int oldTeamsDeleted = Integer.parseInt(document.get("teamsdeleted").toString());
                    int oldTeamsMemberLeave = Integer.parseInt(document.get("memberLeave").toString());

                    int addAccepted = sharedPreferences.getInt("acceptedForMetrics",0);
                    int addRejected = sharedPreferences.getInt("rejectedForMetrics",0);
                    int addRequested = sharedPreferences.getInt("requestedForMetrics",0);
                    int addsm2Appointed = sharedPreferences.getInt("sm2AppointedForMetrics",0);
                    int addTeamsCreated = sharedPreferences.getInt("teamCreatedForMetrics",0);
                    int addTeamsDeleted = sharedPreferences.getInt("teamDeletedForMetrics",0);
                    int playersPerGame = sharedPreferences.getInt("noOfPlayersForMetrics",0);
                    int addTeamsMemberLeave = sharedPreferences.getInt("teamsMemberLeaveForMetrics",0);
                    Log.i("Test6 ", "startupUpdateMetrics: " + addAccepted + " " + addRejected + " " + addRequested + " " + addsm2Appointed + " " + addTeamsCreated + " " + addTeamsDeleted + " " + playersPerGame + " " + addTeamsMemberLeave);

                    int newAccepted = oldAccepted + addAccepted;
                    int newRejected = oldRejected + addRejected;
                    int newRequested = oldRequested + addRequested;
                    int newsm2Appointed = oldsm2Appointed + addsm2Appointed;
                    int newTeamsCreated = oldTeamsCreated + addTeamsCreated;
                    int newTeamsDeleted = oldTeamsDeleted + addTeamsDeleted;
                    int newTeamsMemberLeave = oldTeamsMemberLeave + addTeamsMemberLeave;
                    Log.i("Test7  ", "startupUpdateMetrics: " + newAccepted + " " + newRejected + " " + newRequested + " " + newsm2Appointed + " " + newTeamsCreated + " " + newTeamsDeleted + " " + newTeamsMemberLeave);

                    db.collection("userteammetrics").document(userId).collection("teammetrics").document("generalteammetrics").update("accepted", newAccepted, "rejected", newRejected, "requested", newRequested, "scrummaster2sappointed", newsm2Appointed, "teamscreated", newTeamsCreated, "teamsdeleted", newTeamsDeleted, "memberLeave", newTeamsMemberLeave, "numberofplayerspergame" ,FieldValue.arrayUnion(playersPerGame));

                }
            }
        }
    });
}

LogCat (I don't know why its all appearing twice...hence I thought there might be a leaky thread):

2020-02-01 23:19:28.954 21586-21586/? I/Ads: Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("xxxxxxxxxxxxx") to get test ads on this device.
2020-02-01 23:19:29.026 21586-21586/? I/Ads: Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("xxxxxxxxxxxxx") to get test ads on this device.
2020-02-01 23:19:29.078 21586-21586/? I/ =>: Test1
2020-02-01 23:19:29.078 21586-21586/? I/ =>: Test2 0
2020-02-01 23:19:29.085 21586-21586/? I/ =>: Test1
2020-02-01 23:19:29.085 21586-21586/? I/ =>: Test2 0
2020-02-01 23:19:29.207 21586-21586/? I/Ads: Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("xxxxxxxxxxxxx") to get test ads on this device.
2020-02-01 23:19:29.219 21586-21586/? I/Ads: Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("xxxxxxxxxxxxx") to get test ads on this device.
2020-02-01 23:19:29.344 21586-21586/? I/ =>: Test4 0
2020-02-01 23:19:29.344 21586-21586/? I/ =>: Test5 0
2020-02-01 23:19:29.345 21586-21586/? I/Test6: startupUpdateMetrics: 0 0 0 0 0 0 0 0
2020-02-01 23:19:29.345 21586-21586/? I/Test7: startupUpdateMetrics: 0 0 0 0 0 0 0
2020-02-01 23:19:29.345 21586-21586/? I/ =>: Test4 0
2020-02-01 23:19:29.346 21586-21586/? I/ =>: Test5 0
2020-02-01 23:19:29.346 21586-21586/? I/Test6: startupUpdateMetrics: 0 0 0 0 0 0 0 0
2020-02-01 23:19:29.346 21586-21586/? I/Test7: startupUpdateMetrics: 0 0 0 0 0 0 0
2020-02-01 23:21:04.323 21908-21927/? I/PrimesTesting: GserviceFlagsSupplier.get()
2020-02-01 23:22:40.049 22041-22041/? D/OmtpVvmCarrierCfgHlpr: overrideConfigForTest is null

I'm at a loss with this, any advice would be much appreciated.

Upvotes: 0

Views: 80

Answers (2)

Darkmoon Chief
Darkmoon Chief

Reputation: 140

You can try setting up a Timer to continuously check if setMetrics() has finished executing all its code in order for the deleteMetrics() method to start after.

private static boolean done = false;

Activity_Splash.this.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        setMetrics();
        final Timer t=new Timer();
        t.schedule(new TimerTask() {
        @Override
        public void run() {
        if(done){
        deleteMetrics();
        t.cancel();
        t.purge();
        }
        }
     }, 1000);

    }
});

Assign the boolean value of done to true at the end of setMetrics().

 private void setMetrics() {
        SharedPreferences sharedPreferences = Activity_Splash.this.getSharedPreferences("com.dmurphy.remotescrumpoker", Context.MODE_PRIVATE);
        //Check if device has a network connection
        boolean connectionExists = new NetworkConnection().haveNetworkConnection(passedActivity, TAG);

        //If device has a network connection continue
        if (connectionExists) {
            Log.i(" => ", "Test1");
            try {
                String userId = mAuth.getCurrentUser().getUid();
                int teamCreated2 = sharedPreferences.getInt("teamCreatedForMetrics", 0);
                Log.i(" => ", "Test2 " + teamCreated2);
                callMetrics.startupUpdateMetrics(userId, context);
                done=true;
            } catch (Exception e) {
                Log.e(TAG + "onCreate", "Error setting metrics");
            }
        }
    }

Upvotes: 1

Moonbloom
Moonbloom

Reputation: 7918

This is what happens:

setMetrics() is called first
setMetrics() calls startupUpdateMetrics()
startupUpdateMetrics() calls db.collection... with a callback (the parameter in the addOnCompleteListener call)
deleteMetrics() is called

The callback is done asynchronously.

So you start an asynchronous task, then immediately after that task is started (but not yet completed), you delete all your data.

You need to wait for the callback to occur, and then you can delete your data.

Place the deleteMetrics() as the last line inside the if (document.exists()) brackets.

Upvotes: 1

Related Questions