001/** 002 * Copyright 2011-2015 John Ericksen 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.parceler.converter; 017 018import android.os.Parcel; 019import android.util.SparseArray; 020import org.parceler.ParcelConverter; 021 022/** 023 * @author John Ericksen 024 */ 025public abstract class SparseArrayParcelConverter<T> implements ParcelConverter<SparseArray<T>> { 026 @Override 027 public void toParcel(SparseArray<T> input, Parcel parcel) { 028 if (input == null) { 029 parcel.writeInt(-1); 030 } else { 031 parcel.writeInt(input.size()); 032 for (int i = 0; (i < input.size()); i++) { 033 parcel.writeInt(input.keyAt(i)); 034 itemToParcel(input.valueAt(i), parcel); 035 } 036 } 037 } 038 039 @Override 040 public SparseArray<T> fromParcel(Parcel parcel) { 041 SparseArray<T> array; 042 int size = parcel.readInt(); 043 if (size < 0) { 044 array = null; 045 } else { 046 array = new SparseArray<T>(size); 047 for (int i = 0; (i < size); i++) { 048 int key = parcel.readInt(); 049 array.append(key, itemFromParcel(parcel)); 050 } 051 } 052 return array; 053 } 054 055 public abstract void itemToParcel(T input, Parcel parcel); 056 public abstract T itemFromParcel(Parcel parcel); 057}