how to clone an object in android?

Make sure that your DataObj class implements Cloneable and add the following method

protected Object clone() throws CloneNotSupportedException {
        return super.clone();
}

Then you should be able to call (DataObj)rlBodyDataObj.clone(); to get a clean copy (note the cast).


you can implements Parcelable (easy with studio plugin), and then

public static <T extends Parcelable> T copy(T orig) {
    Parcel p = Parcel.obtain();
    orig.writeToParcel(p, 0);
    p.setDataPosition(0);
    T copy = null;
    try {
        copy = (T) orig.getClass().getDeclaredConstructor(new Class[]{Parcel.class}).newInstance(p);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return copy;
}

class Test implements Cloneable
  {
   ...
      public Object clone()
      {
          try
      {
              return super.clone();
          }
      catch( CloneNotSupportedException e )
      {
              return null;
          }
      } 
  ...
  }

Tags:

Java

Android