1

I am having this weird problem where the intent.getParcelableExtra() is working fine on API 23 but not on API 25, it is returning NULL.

Here is how I reproduced the problem with less code:

User class as example:

public class User implements Parcelable {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age =age;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeString(name);
        out.writeInt(age);
    }

    public User(Parcel in) {
        this.name = in.readString();
        this.age = in.readInt();
    }

    public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
        @Override
        public User createFromParcel(Parcel source) {
            return new User(source);
        }

        @Override
        public User[] newArray(int size) {
            return new User[size];
        }
    };
 }

MainActivity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        /*setting view*/

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, AlarmReceiver.class);
        User user = new User("test", 25);
        intent.putExtra("user", user);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 3000, pendingIntent);

    }
}

And the receiver:

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        android.os.Debug.waitForDebugger();
        User user = intent.getParcelableExtra("user");
    }
}

I am using the debugger to stop execution and evaluate the user object in the receiver.

When using the emulator Android 6.0 API level 23 : the user is passed correctly, but when using my phone Android 7.1.2 API level 25 : the user is NULL

Any help is appreciated.

hiddeneyes02
  • 2,562
  • 1
  • 31
  • 58

1 Answers1

0

Thanks to CommonsWare, I was able to understand the problem. It seems to be related to Android and there is nothing we can do about it, except use workarounds.

For those who still want to use Parcelable, use this: How to marshall and unmarshall a Parcelable to a byte array with help of Parcel?

For me, I saved the object I want to pass into a file (using json), then I passed the name of the file as a string to the AlarmManager, then read the file in the receiver.

hiddeneyes02
  • 2,562
  • 1
  • 31
  • 58