1

If i have an object form interface in my class, how i can pass it to activity?

My solution was to change it as static object, it's work fine but sometimes it create a memory leaks because of all the old references which the garbage collector cannot collect, and i cannot implement 'Serializable' on my interface.

public class MyClass {
     protected OnStringSetListener onstringPicked;
        public interface OnStringSetListener {
            void OnStringSet(String path);

        }
    //......//
      public void startActivity(){
                Intent intent=new Intent(context,Secound.class);
                // ?! intent.putExtra("TAG", inter);
                context.startActivity(intent);
      }
}
Chintan Soni
  • 24,761
  • 25
  • 106
  • 174
Abdullah AlHazmy
  • 1,299
  • 1
  • 13
  • 22

2 Answers2

0

Passing in custom objects is a little more complicated. You could just mark the class as Serializable and let Java take care of this. However, on the android, there is a serious performance hit that comes with using Serializable. The solution is to use Parcelable.

Extra info

Community
  • 1
  • 1
Ahmad Aghazadeh
  • 16,571
  • 12
  • 101
  • 98
0

In my opinion, using Bundles would be a nice choice. Actually bundles internally use Parcelables. So, this approach would be a good way to go with.

Suppose you would like to pass an object of type class MyClass to another Activity, all you need is adding two methods for compressing/uncompressing to/from a bundle.

To Bundle:

public Bundle toBundle(){
    Bundle bundle = new Bundle();
    // Add the class properties to the bundle
    return bundle;
}

From Bundle:

public static MyClass fromBundle(Bundle bundle){
    MyClass obj = new MyClass();
    // populate properties here
    return obj;
}

Note: Then you can simply pass bundles to another activities using putExtra. Note that handling bundles is much simpler than Parcelables.

frogatto
  • 28,539
  • 11
  • 83
  • 129