How to transfer a link (non-serializable) from one operation to another?

Say that I have a reference to an object, how should I transfer this from one action to another?

I do not want to query the Application / singleletons / static variables object.

Is it possible?

+5
source share
3 answers

You can declare a static variable in another activity or some global variable in the Application class, and then access it for any action, for example, you want to parse some object of type NewType, in Class NewActivity, from OldActivity. Do the following:

Declare a Static NewType object in NewActivity.java.

public static NewObject newObject=null; 

do After that, when you call NewActivity.

 NewActivity.newObject=item; Intent intent=new Intent(OldActivity.this, NewActivity.class); startActivity(intent); 
+7
source

You can do this in one of the following ways:

  • Make a Static Object. (easiest, but not always effective).
  • Serialize -> send -> accept -> deserialize. You can use something like JSON decoding and encoding if your class is not serializable. (Involves a lot over your head; you do not want to use this unless you have a good reason.)
  • Original (most effective, fastest)

Here, for example, from the documents: you can wrap your object with parcelable , attach it to the intent and "wrap" it in the host activity.

  public class MyParcelable implements Parcelable { private int mData; public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeInt(mData); } public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() { public MyParcelable createFromParcel(Parcel in) { return new MyParcelable(in); } public MyParcelable[] newArray(int size) { return new MyParcelable[size]; } }; private MyParcelable(Parcel in) { mData = in.readInt(); } } 
+1
source

One solution:

You can make a singleton class to transfer the required information.

eg:

 StorageManager.getInstance().saveSomething(Object obj); 

then push back using the appropriate getter method

Make sure you care about synchronization issues;)

-1
source

Source: https://habr.com/ru/post/975855/


All Articles