-1

I have an activity that I go back and forth in it. but I want this code to run once inside it even if I switch activity.

//get the Current user id(uid)
    userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
    Log.i("UID",userId);
    orderDatabaseReference = FirebaseDatabase.getInstance().getReference("Orders").child(userId);
    id = orderDatabaseReference.push().getKey();

I know the methods onStart, onResume ... but they are also the same

Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77

2 Answers2

3

If you go from one activity to another and come back, all your methods will fire again since the lifecycle starts again, this also happens when you rotate your device, for better understanding about how to persist data, you can see this, if you want to know about Android lifecycle, read this and this

You can use ViewModel as part of the Android Architecture Components.

Guide to app architecture

ViewModel documentation

You can also use Room if you want to persist the data locally.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
1

Most likely you want to put this code in onCreate() which is run once when the Activity instance is created. It won't run when the user goes to another activity and comes back unless the first activity is destroyed in the mean time. But then most likely you need to refresh your connection to Firebase anyway. As Gaston points out in his answer, you need to learn about the entire Android lifecycle and understand when each event fires in order to decide where to write write your code.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • As one more thing, when @Code-Apprentice points out destroying an activity is when you put `finish()` navigating to other activity or kill the activity in the foreground with your home button – Gastón Saillén Mar 11 '20 at 20:30
  • @GastónSaillén Also, the system may choose to destroy the activity whenever it needs to free resources or in response to a system event such as orientation change. These are more what I had in mind here. – Code-Apprentice Mar 11 '20 at 20:33
  • 2
    @GastónSaillén Just to note, early Android documentation stated that individual activities can be killed, but that is not the case. Only processes are killed if the system needs to free up memory. See here: https://stackoverflow.com/a/34971387/4409409 And also see here: https://stackoverflow.com/questions/7536988/android-app-out-of-memory-issues-tried-everything-and-still-at-a-loss/7576275#7576275 – Daniel Nugent Mar 11 '20 at 21:26
  • 1
    @DanielNugent Thanks for the clarification. This is something I was not aware of. – Code-Apprentice Mar 11 '20 at 21:28