使用Retrofit 2.0 + RxJava + Realm + RecyclerView不会将数据保存到DB中

时间:2016-05-19 14:42:20

标签: java android realm rx-java retrofit2

我对Android和第三方库很新,所以我有一个问题。 我想将一些来自REST API的数据存储到Realm中,然后将其显示到RecyclerView中。我有三个选项卡使用相同的recyclerView,因此它可以显示三种不同的状态。 这是我的课程:

public class RealmContentAdapter extends RealmRecyclerViewAdapter<ContentDataModel, RealmContentAdapter.ViewHolder> {
private Context mContext;


public static class ViewHolder extends RecyclerView.ViewHolder{
    private ImageView cardIcon;
    private TextView likeCounter, cardHeader, cardAddress, cardDate, cardDays;

    public ViewHolder(View itemView) {
        super(itemView);
        this.cardIcon = (ImageView) itemView.findViewById(R.id.card_icon);
        this.likeCounter = (TextView) itemView.findViewById(R.id.like_counter);
        this.cardHeader = (TextView) itemView.findViewById(R.id.card_header_text);
        this.cardAddress = (TextView) itemView.findViewById(R.id.card_address_text);
        this.cardDate = (TextView) itemView.findViewById(R.id.card_date_text);
        this.cardDays = (TextView) itemView.findViewById(R.id.card_days_text);
    }
}

public RealmContentAdapter (Context context, OrderedRealmCollection<ContentDataModel> data){
    super(context, data, true);
    mContext = context;

}



@Override
public RealmContentAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.card_item, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(RealmContentAdapter.ViewHolder holder, int position) {
    ContentDataModel model = getData().get(position);
    holder.likeCounter.setText(String.valueOf(model.getLikesCounter()));
    holder.cardHeader.setText(model.getTitle());
    holder.cardIcon.setImageResource(R.drawable.nature);
    if (model.getGeoAddress() != null){
        holder.cardAddress.setText(model.getGeoAddress().getAddress());
    } else {
        holder.cardAddress.setText("");
    }

    holder.cardDate.setText(model.getNormalDate());
    holder.cardDays.setText(String.valueOf(model.getDays()));

}


public class ContentDataModel extends RealmObject {

@SerializedName("id")
@Expose
private int id;
@SerializedName("user")
@Expose
private User user;
@SerializedName("geo_address")
@Expose
private GeoAddress geoAddress;
@SerializedName("category")
@Expose
private Category category;
@SerializedName("type")
@Expose
private Type type;
@SerializedName("title")
@Expose
private String title;
@SerializedName("body")
@Expose
private String body;
@SerializedName("created_date")
@Expose
private int createdDate;
@SerializedName("start_date")
@Expose
private int startDate;
@SerializedName("state")
@Expose
private State state;
@SerializedName("ticket_id")
@Expose
private String ticketId;
@SerializedName("files")
@Expose
@Ignore
private List<Files> files = new ArrayList<>();
@SerializedName("performers")
@Expose
@Ignore
private List<Performer> performers = new ArrayList<>();
@SerializedName("deadline")
@Expose
private int deadline;
@SerializedName("likes_counter")
@Expose
private int likesCounter;


public int getId() {
    return id;
}


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


public User getUser() {
    return user;
}


public void setUser(User user) {
    this.user = user;
}


public GeoAddress getGeoAddress() {
    return geoAddress;
}


public void setGeoAddress(GeoAddress geoAddress) {
    this.geoAddress = geoAddress;
}


public Category getCategory() {
    return category;
}


public void setCategory(Category category) {
    this.category = category;
}


public Type getType() {
    return type;
}


public void setType(Type type) {
    this.type = type;
}


public String getTitle() {
    return title;
}


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


public String getBody() {
    return body;
}


public void setBody(String body) {
    this.body = body;
}


public int getCreatedDate() {
    return createdDate;
}


public void setCreatedDate(int createdDate) {
    this.createdDate = createdDate;
}


public int getStartDate() {
    return startDate;
}


public void setStartDate(int startDate) {
    this.startDate = startDate;
}


public State getState() {
    return state;
}


public void setState(State state) {
    this.state = state;
}


public String getTicketId() {
    return ticketId;
}


public void setTicketId(String ticketId) {
    this.ticketId = ticketId;
}


public List<Files> getFiles() {
    return files;
}


public void setFiles(List<Files> files) {
    this.files = files;
}


public List<Performer> getPerformers() {
    return performers;
}


public void setPerformers(List<Performer> performers) {
    this.performers = performers;
}


public int getDeadline() {
    return deadline;
}


public void setDeadline(int deadline) {
    this.deadline = deadline;
}


public int getLikesCounter() {
    return likesCounter;
}


public void setLikesCounter(int likesCounter) {
    this.likesCounter = likesCounter;
}

public String getNormalDate(){
    return DateFormatter.getNormalDate(getStartDate());
}

public String getDays(){
    return DateFormatter.getGoneDays(getStartDate());
}

我有一些其他的pojo课程,但这个是主要课程。 我的Recycler Fragment:

public class RecyclerFragment extends Fragment {
private static final String KEY_FILE = "file";
private RealmContentAdapter mAdapter;
private RealmResults<ContentDataModel> mData;
private RecyclerView mRecyclerView;
private Realm mRealm;

public static Fragment newInstance(String file) {
    RecyclerFragment fragment = new RecyclerFragment();
    Bundle args = new Bundle();
    args.putString(KEY_FILE, file);
    fragment.setArguments(args);
    return fragment;
}

public String getPage() {
    return (getArguments().getString(KEY_FILE));
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.recycler_fragment_layout, container, false);
    mIntent = new Intent(getContext(), CardActivity.class);

    mRealm = Realm.getDefaultInstance();
    mData = mRealm.where(ContentDataModel.class).findAll();

    ApiService apiService = ApiModule.getApiService();
    Observable<List<ContentDataModel>> tabOneContent = apiService.loadCards(
            getString(R.string.processing_state), 10);
    Observable<List<ContentDataModel>> tabTwoContent = apiService.loadCards(
            getString(R.string.done_state), 10);
    Observable<List<ContentDataModel>> tabThreeContent = apiService.loadCards(
            getString(R.string.pending_state), 10);

    mRecyclerView = (RecyclerView) view.findViewById(R.id.tab_recycler);
    mRecyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(),
            LinearLayoutManager.VERTICAL, false);
    mRecyclerView.setLayoutManager(layoutManager);
    mAdapter = new RealmContentAdapter(getContext(), mData);
    mRecyclerView.setAdapter(mAdapter);

    if (getPage().equals(getString(R.string.processing_flag))) {
       tabOneContent
               .subscribeOn(Schedulers.io())
               .observeOn(AndroidSchedulers.mainThread())
               .subscribe(new Subscriber<List<ContentDataModel>>() {
                   @Override
                   public void onCompleted() {

                   }

                   @Override
                   public void onError(Throwable e) {

                   }

                   @Override
                   public void onNext(List<ContentDataModel> dataSet) {
                       Realm realm = Realm.getDefaultInstance();
                       realm.beginTransaction();
                       realm.copyToRealm(dataSet);
                       realm.commitTransaction();
                       realm.close();
                   }
               });
    } else if (getPage().equals(getString(R.string.done_flag))) {
        tabTwoContent
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<ContentDataModel>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<ContentDataModel> dataSet) {
                        Realm realm = Realm.getDefaultInstance();
                        realm.beginTransaction();
                        realm.copyToRealm(dataSet);
                        realm.commitTransaction();
                        realm.close();
                    }
                });
    } else if (getPage().equals(getString(R.string.pending_flag))) {
        tabThreeContent
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<ContentDataModel>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<ContentDataModel> dataSet) {
                        Realm realm = Realm.getDefaultInstance();
                        realm.beginTransaction();
                        realm.copyToRealm(dataSet);
                        realm.commitTransaction();
                        realm.close();
                    }
                });
    }


    return view;
}

问题是当我尝试将List数据集保存到Realm时,它不会保存任何数据集。我的RealmContentAdapter是空的。

P.S。:我仔细设置了GSON,它忽略了RealmObject.class

UPD:所以,我发现了什么是错的。 Realm不想保存数据,因为我错过了将@PrimaryKey添加到id中的字段ContentDataModel。谢谢你的关注。

0 个答案:

没有答案