Проблем при анализиране на данни в Intent

Ето това е нещото

  • Имам услуга, която изтегля данни от функциите на уеб услугата

  • Искам да предам резултата от изтеглянията през Intent към Broadcast, след което да извлека данните вътре в Activities, Fragments, ...

  • Всички мои обекти с данни са генерирани от GreenDAO, L добави само „implements Parcelable“, за да ги анализира в Intent.

  • Имам проблем с анализирането на тези обекти, тъй като някои имат и списък с парцелируеми вътре. Получавам грешки „parcelable Unmarshalling unknown type“ в моите BroadcastReceivers

Ето част от моя код:

Обектен подкаст

public class Podcast implements Parcelable {

    private static final String     TAG             = Podcast.class.getSimpleName();
    private long                    id;
    private String                  title;
    private String                  subtitle;
    private String                  summary;
    private String                  duration;
    private String                  author;
    private String                  date;
    private String                  mp3;
    private long                    podcastCategoryId;
    /** Used to resolve relations */
    private transient DaoSession    daoSession;
    /** Used for active entity operations. */
    private transient PodcastDao    myDao;
    private List<Enclosure>         mEnclosureList  = new ArrayList<Enclosure>();

    public Podcast() {
    }

    public Podcast(long id) {
        this.id = id;
    }

    public Podcast(long id, String title, String subtitle, String summary, String duration, String author, String date, String mp3, long podcastCategoryId) {
        this.id = id;
        this.title = title;
        this.subtitle = subtitle;
        this.summary = summary;
        this.duration = duration;
        this.author = author;
        this.date = date;
        this.mp3 = mp3;
        this.podcastCategoryId = podcastCategoryId;
    }

    /** called by internal mechanisms, do not call yourself. */
    public void __setDaoSession(DaoSession daoSession) {
        this.daoSession = daoSession;
        myDao = daoSession != null ? daoSession.getPodcastDao() : null;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSubtitle() {
        return subtitle;
    }

    public void setSubtitle(String subtitle) {
        this.subtitle = subtitle;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public String getDuration() {
        return duration;
    }

    public void setDuration(String duration) {
        this.duration = duration;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getMp3() {
        return mp3;
    }

    public void setMp3(String mp3) {
        this.mp3 = mp3;
    }

    public long getPodcastCategoryId() {
        return podcastCategoryId;
    }

    public void setPodcastCategoryId(long podcastCategoryId) {
        this.podcastCategoryId = podcastCategoryId;
    }

    /**
     * To-many relationship, resolved on first access (and after reset). Changes to to-many relations are not persisted, make changes to the target
     * entity.
     */
    public List<Enclosure> getMEnclosureList() {
        if (mEnclosureList == null) {
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            EnclosureDao targetDao = daoSession.getEnclosureDao();
            List<Enclosure> mEnclosureListNew = targetDao._queryPodcast_MEnclosureList(id);
            synchronized (this) {
                if (mEnclosureList == null) {
                    mEnclosureList = mEnclosureListNew;
                }
            }
        }
        return mEnclosureList;
    }

    /** Resets a to-many relationship, making the next get call to query for a fresh result. */
    public synchronized void resetMEnclosureList() {
        mEnclosureList = null;
    }

    /** Convenient call for {@link AbstractDao#delete(Object)}. Entity must attached to an entity context. */
    public void delete() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.delete(this);
    }

    /** Convenient call for {@link AbstractDao#update(Object)}. Entity must attached to an entity context. */
    public void update() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.update(this);
    }

    /** Convenient call for {@link AbstractDao#refresh(Object)}. Entity must attached to an entity context. */
    public void refresh() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.refresh(this);
    }

    public List<Enclosure> getmEnclosureObjectList() {
        return mEnclosureList;
    }

    @Override
    public String toString() {
        return String.format("%s - %s - %s - %s - %s - %s - %s \n", this.id, this.title, this.subtitle, this.author, this.duration, this.mp3, this.date);
    }

    public void addEnclocureToList(Enclosure enclosure) {
        Log.d(TAG, "hehe : " + enclosure);
        if (mEnclosureList == null) {
            mEnclosureList = new ArrayList<Enclosure>();
        }
        mEnclosureList.add(enclosure);
    }

    public void setEnclosureList(List<Enclosure> list) {
        mEnclosureList = list;
    }

    public Podcast(Parcel parcel) {
        id = parcel.readLong();
        title = parcel.readString();
        subtitle = parcel.readString();
        summary = parcel.readString();
        duration = parcel.readString();
        author = parcel.readString();
        date = parcel.readString();
        mp3 = parcel.readString();
        podcastCategoryId = parcel.readLong();
        parcel.readTypedList(mEnclosureList, Enclosure.CREATOR);
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(id);
        dest.writeString(title);
        dest.writeString(subtitle);
        dest.writeString(summary);
        dest.writeString(duration);
        dest.writeString(author);
        dest.writeString(date);
        dest.writeString(mp3);
        dest.writeLong(podcastCategoryId);
        dest.writeTypedList(mEnclosureList);
    }

    public static Creator<Podcast>  CREATOR = new Creator<Podcast>() {

                                                public Podcast createFromParcel(Parcel parcel) {
                                                    return new Podcast(parcel);
                                                }

                                                public Podcast[] newArray(int size) {
                                                    return new Podcast[size];
                                                }
                                            };
}

Обектът, който се съдържа в списъка:

public class Enclosure implements Parcelable {

    private long    id;
    private String  enclosure;
    private long    podcastId;

    public Enclosure() {
    }

    public Enclosure(long id) {
        this.id = id;
    }

    public Enclosure(long id, String enclosure, long podcastId) {
        this.id = id;
        this.enclosure = enclosure;
        this.podcastId = podcastId;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getEnclosure() {
        return enclosure;
    }

    public void setEnclosure(String enclosure) {
        this.enclosure = enclosure;
    }

    public long getPodcastId() {
        return podcastId;
    }

    public void setPodcastId(long podcastId) {
        this.podcastId = podcastId;
    }

    @Override
    public String toString() {
        return String.format("%s - %s - %s", this.id, this.enclosure, this.podcastId);
    }

    public Enclosure(Parcel parcel) {
        parcel.writeLong(id);
        parcel.writeString(enclosure);
        parcel.writeLong(podcastId);
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(id);
        dest.writeString(enclosure);
        dest.writeLong(podcastId);
    }

    public static Creator<Enclosure>    CREATOR = new Creator<Enclosure>() {

                                                    public Enclosure createFromParcel(Parcel parcel) {
                                                        return new Enclosure(parcel);
                                                    }

                                                    public Enclosure[] newArray(int size) {
                                                        return new Enclosure[size];
                                                    }
                                                };
}

Как изпращам данните (данните са добре, проверих ги точно преди sendBroadcast()):

private void sendBroadcastEvent(DownloadState state, ArrayList<Parcelable> result) {
        Intent intent = null;
        intent = new Intent(mDownloadDataType);
        intent.putExtra(INTENT_DOWNLOAD_STATE, mDownloadState);
        switch (state) {
            case STARTED:
                break;
            case FAILED:
                break;
            case SUCCEDED:
                intent.putParcelableArrayListExtra(INTENT_DOWNLOAD_CONTENT, result);
                break;
            case NO_NETWORK:
                break;
        }
        mContext.sendBroadcast(intent);
    }

Енумът е точно това:

public enum DownloadState {
    STARTED, FAILED, SUCCEDED, NO_NETWORK
}

Сега как получавам данните:

частен BroadcastReceiver mDownloadReceiver;

...

mDownloadReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String actionString = intent.getAction();
                state = (DownloadState) intent.getExtras().getSerializable(DownloadTask.INTENT_DOWNLOAD_STATE);
                switch (state) {
                    case SUCCEDED:
                        List<?> list = intent.getExtras().getParcelableArrayList(DownloadTask.INTENT_DOWNLOAD_CONTENT);
                        if (actionString == ServiceDataDownload.INTENT_DOWNLOAD_PODCASTS) {
                            try {
                                RadioApplication.mDataManagerInstance.addToPodcastMap(mPodcastCategory.getTitle(), (List<Podcast>) list);
                                mList = (List<Podcast>) list;
                                Log.d(TAG, "podcasts : " + mList.toString());
                                updateAdapter(mList, mContext);
                            }
                            catch (Exception e) {
                                // just in case for now
                            }
                        }
                        break;
                    case FAILED:
                        break;
                    case NO_NETWORK:
                        break;
                    case STARTED:
                        break;
                }
            }
        };

...

Приемниците са регистрирани правилно, всичко работеше ДОБРЕ и всичко, докато не добавих вложен списък на пакетиране на заграждение в пакета на подкаст.

Имате ли представа?


person An-droid    schedule 24.01.2014    source източник
comment
Мисля, че е по-лесно да предадете идентификатора на данните, които искате да сериализирате в parcelable за намерението и да направите заявката в излъчването...   -  person phemt.latd    schedule 24.01.2014
comment
Това би било твърде сложно, това е малка част от проекта. Имам много изтегляния, които трябва да управлявам едновременно, повторен опит, спиране, .. и т.н. услуга за управление на задачите и нишките..   -  person An-droid    schedule 24.01.2014
comment
Разрешено в класа Enclosure, който използвам write, когато очевидно трябва да прочета в колета... в метода public Enclosure(Parcel parcel) {}   -  person An-droid    schedule 29.01.2014


Отговори (1)


Това беше глупава грешка:

   public Enclosure(Parcel parcel) {
        id = parcel.readLong();
        enclosure = parcel.readString();
        podcastId = parcel.readLong();
    }

Ако пиша, вместо да чета, няма да работи, разбира се

РЕШЕНО

person An-droid    schedule 29.01.2014