Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Using Parcelable in Android

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 196
    Comment on it

    In simple words , Send the complete object to other views like (switching b/w different Activity).

    What if you need to send 50 value to other Activity, Don't write 50 putExtra to your code as it will increase the size of code ,just use Parcelable

    Ignore sending every fields in putExtra to other Activity , use Parcelable to send Complete object to other Class.

    IMPLEMENTING YOUR CLASS WITH PARCELABLE

    1. public class Student implements Parcelable{
    2.  
    3. String Name;
    4. int Age;
    5.  
    6. @Override
    7. public int describeContents() {
    8. // TODO Auto-generated method stub
    9. return 0;
    10. }
    11.  
    12. /**
    13. * Storing the Student data to Parcel object
    14. **/
    15. @Override
    16. public void writeToParcel(Parcel dest, int flags) {
    17. dest.writeString(Name);
    18. dest.writeInt(Age);
    19. // write as much as variable you need
    20.  
    21. }
    22.  
    23. /**
    24. * A constructor that initializes the Student object
    25. **/
    26. public Student(String sName, int sAge){
    27. this.Name = sName;
    28. this.Age = sAge;
    29.  
    30. }
    31.  
    32. /**
    33. * Retrieving Student data from Parcel object
    34. * This constructor is invoked by the method createFromParcel(Parcel source) of
    35. * the object CREATOR
    36. **/
    37. private Student(Parcel in){
    38. this.Name = in.readString();
    39. this.Age = in.readInt();
    40.  
    41. }
    42.  
    43. public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
    44.  
    45. @Override
    46. public Student createFromParcel(Parcel source) {
    47. return new Student(source);
    48. }
    49.  
    50. @Override
    51. public Student[] newArray(int size) {
    52. return new Student[size];
    53. }
    54. };
    55. }
    56.  
    57.  

    PASS the complete class in INTENT

    1. intent.putExtra("student",student);

    // Get data from a parcelable object

    1. Student student = getIntent().getParcelableExtra("student");

    NOTE :Reading and writing the value into parcel should be in same order ,otherwise you will get incorrect values.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: