ParcelablePlease


Source link: https://github.com/sockeqwe/ParcelablePlease

ParcelablePlease

An AnnotationProcessor for generating Android Parcelable boilerplate code. See this blog entry for comparison with other parcel libraries.

Dependency

Latest version:

compile 'com.hannesdorfmann.parcelableplease:annotation:x.x.x' apt 'com.hannesdorfmann.parcelableplease:processor:x.x.x'

In android studio you need to apply Hugo Visser's awesome android-apt gradle plugin to enable annotation processing.

How to use

Simply annotate the classes you want to make Parcelable with @ParcelablePlease and implement the Parcelable as well as the CREATOR (This step can be automated by using the Android Studio plugin, see below).

@ParcelablePlease public class Model implements Parcelable {

 int id;
String name;
OtherModel otherModel;
 @Override public int describeContents() {

  return 0;

}

 @Override public void writeToParcel(Parcel dest, int flags) {

  ModelParcelablePlease.writeToParcel(this, dest, flags);

}

 public static final Creator<Model> CREATOR = new Creator<Model>() {

  public Model createFromParcel(Parcel source) {

 Model target = new Model();

 ModelParcelablePlease.readFromParcel(target, source);

 return target;
  
}

public Model[] newArray(int size) {

 return new Model[size];
  
}

}
; 
}
 

The ParcelablePlease annotation processor will generate a class named ClassName + ParcelablePlease for you with all the code for writing and reading data in the Parcel. So from the example above: ModelParcelablePlease is generated and provides two static methods: ModelParcelablePlease.readFromParcel(Model, Parcel) and ModelParcelablePlease.writeToParcel(Model, Parcel, int)

Once you have done this basic setup by connecting the generated code with your Model class you can change the model class, add fields, remove fields etc. without worring about Parcelable because ParcelablePlease will generate the code for you everytime you compile.

Android Studio Plugin

Like mentioned above you have to write few lines of code to connect the Parcelable class with the generated code. Don't worry, you don't have to do this by hand. There is a Android Studio / IntelliJ plugin that can do that for you:

  1. Open Android Studio / IntelliJ
  2. Open the Preferences (on Mac with ? + ; )
  3. Type in the searchbox "plugin" to navigate quickly to the plugins section
  4. Click on Browse repositories... button
  5. Search for ParcelablePlease and install this plugin
  6. Restart Android Studio
  7. Create a Model class and open the Generate Menu (on Mac with ``? + n` ). Note that the cursor must be somewhere in the code of the class.

Remember that you may have to compile your project to make Android Studio run annotation Processing which will generate the ParcelPlease classes.

Supported types

  • Primitives

    • byte
    • boolean
    • double
    • float
    • int
    • long
    • String
  • Primitive wrappers

    • Byte
    • Boolean
    • Double
    • Float
    • Int
    • Long
  • Android specific

    • Parcelable (anything that implements Parcelable)
    • Bundle
    • SparseBooleanArray
  • Arrays

    • int[]
    • long[]
    • double[]
    • String[]
    • float[]
    • char[]
    • boolean[]
    • byte[]
    • Parcelable[] - array of anything that implements Parcelable
  • Other

    • Serializable
    • java.util.Date (by simpling passing time as millis)
  • Collections

    • List<? extends Parcelalble>
    • ArrayList<? extends Parcelable>
    • LinkedList<? extends Parcelable>
    • CopyOnWriteArrayList<? extends Parcelable>
    • List

Bagger

Do you want to make a field Parcelable but it's not listed in the supported types list from above (i.e. java.util.Map)? No Problem: You can provide your own implementation implementing a ParcelBagger like this:

public class DateBagger implements ParcelBagger<Date> {

 @Override public void write(Date value, Parcel out, int flags) {

  if (value == null) {

 out.writeLong(-1);

  
}
 else {

 out.writeLong(value.getTime());

  
}

}

 @Override public Date read(Parcel in) {

long timeMillis = in.readLong();

  if (timeMillis == -1) {

 return null;
  
}

return new Date(timeMillis);

}
 
}

You can use your ParcelBagger with the @Bagger annotation like this:

@ParcelablePlease public class Person implements Parcelable {

 int id;
String name;

@Bagger(DateBagger.class)
Date date;
 
}

Remember that you have to take care about special cases like what if the value is null. Note that java.util.Date is already supported by ParcelablePlease. The example above is just to give you an idea of how a implementation could look like.

Configuration

You can configure which fields should be serialized. There are two ways:

  1. As default all class (and super classes) fields will be serialized. You can mark field's you don't want to serialize by annotating them with @ParcelableNoThanks
  2. You can do the other way: You could change the settings to only serialize fields that are marked with @ParcelableThisPlease like this:
@ParcelablePlease( allFields = false) public class Animal implements Parcelable {

  @ParcelableThisPlease
 String name;

  int age; // This will not be serialized 
  
}

As default ParcelablePlease will throw a compile error if it tries to serialize private fields (private fields are not supported because of visibility issues). If your class marked with @ParcelablePlease contains private fields you could mark them as not parcelable with @ParcelableNoThanks or you could cofigure ParcelablePlease to skip private fields by using @ParcelablePlease( ignorePrivateFields = true):

@ParcelablePlease( ignorePrivateFields = true) public class Person implements Parcelable {

  String name;

  private int age; // No compile error 
  
}

Limitations

  • Fields must have at least default (package) visibility. That means private fields are not supported.
  • Private classes are not supported because of visibilitiy issues

Resources

An Android image transformation library providing cropping above Face Detection for Glide.

Library what helps getting photo or video from device gallery, from a cloud or from a camera.

This plugin configures JavaCompile tasks to use the error-prone compiler.

Simple lightweight MVP library for Android.

iOS uses 3D Touch as a way to "peek" into full content, such as emails, pictures, web searches, etc. While they have dedicated hardware for this functionality, it is still possible to get similar functionality out of Android, with a long click, rather than the dedicated hardware.

This library aims to create a simple and powerful API to enable 3D Touch style "Peeking" on Android.

Simple library to use text input layout with spinner.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes