How to pass an object from one activity to another on Android

后端 未结 30 3979
遇见更好的自我
遇见更好的自我 2020-11-21 04:03

I am trying to work on sending an object of my customer class from one Activity and display it in another Activity.

The code for t

30条回答
  •  离开以前
    2020-11-21 05:06

    1. I know that static is bad, but it seems that we're forced to use it here. The problem with parceables/seriazables is that the two activities have duplicate instances of the same object = waste of memory and CPU.

      public class IntentMailBox {
          static Queue content = new LinkedList();
      }
      
      
      
      

      Calling activity

      IntentMailBox.content.add(level);
      Intent intent = new Intent(LevelsActivity.this, LevelActivity.class);
      startActivity(intent);
      

      Called activity (note that onCreate() and onResume() may be called multiple times when the system destroys and recreates activities)

      if (IntentMailBox.content.size()>0)
          level = (Level) IntentMailBox.content.poll();
      else
          // Here you reload what you have saved in onPause()
      
      1. Another way is to declare a static field of the class that you want to pass in that very class. It will serve only for this purpose. Don't forget that it can be null in onCreate, because your app package has been unloaded from memory by system and reloaded later.

      2. Bearing in mind that you still need to handle activity lifecycle, you may want to write all the data straight to shared preferences, painful with complex data structures as it is.

      提交回复
      热议问题