2

Target - Android 4.1.2

I need to save instance of custom class object and transfer it to another activities. I was created a simple class ObjectTransfer:

public  class ObjectTransfer {
private static Object TransfObj;

public static void setTransferObj(Object trObj){
    TransfObj = trObj;
}

public static Object getTraObject(){
    Object retObj =TransfObj;
    TransfObj = null;
    return retObj;
}

in source activity :

ObjectTransfer.setTransferObj(MyCustom);

in dest. activity :

MyCustom = (MyCustom) ObjectTransfer.getTraObject();

It's work for me, but some times MyCustom become to null in ObjectTransfer.

Please help me solve my problem!

Sorry for my English.

GIKO
  • 175
  • 1
  • 2
  • 11

4 Answers4

1

When moving between activities, Android can kill your application before starting the new activity. In this case you will loose data. How ever this is a rare case and it more happens when returning from home screen.

The best practice is using intents to deliver data. To encode the entire Object you need to use Intent.putExtra() and your object need to be Parcelable.

EDIT: Just thought about another reason for this to happen. Your code is not synchronized, you may have a bug of threads synchronization. Try adding synchronization block there.

Ilya Gazman
  • 31,250
  • 24
  • 137
  • 216
  • Parcelable not work. Because i need to store very difficult structure in my custom class object – GIKO Nov 26 '13 at 15:31
  • @GIKO I don't think you got any other choices here. You can also use Serializable and store it in the DB, but it will be the same. If your static is null it's only because your app crashed. – Ilya Gazman Nov 26 '13 at 15:35
0

Make your ObjectTransfer implement Serializable:

public class ObjectTransfer implements Serializable{

Pass Object in First Activity:

Intent in=new Intent(FirstActivity.this,SecondActivity.class);
in.putExtra("obj", obj);
startActivity(in);

Get Object in second Activity:

ObjectTransfer ap = (ObjectTransfer) getIntent().getSerializableExtra("obj");
0

Have your custom object implement the Parcelable interface then add the object as an extra to the Intent used to start your other activity. The other activity can then peel the custom object out of the Intent properly. This has the added benefit that if your activities are ever in separate processes (i.e. different packages) it will still work as Parcelable objects are Android's way of efficiently moving data across processes.

Larry Schiefer
  • 15,687
  • 2
  • 27
  • 33
0

I found decision. I declared

MyCustom as public static MyCustomClass MyCutom;

in first activity class. In another activities I give access by using:

firstActivity.MyCustom.somFunction();

I don't known correct it's or not, but it work for me. Thanks to Babibu for idea about store in DB. It's work for me too (perhaps more correctly), but I not have a much time to write this code.

GIKO
  • 175
  • 1
  • 2
  • 11