[英]How can I map two models from different data sources?
I'm facing an issue in a project I'm currently developing. 我正在开发的项目中遇到一个问题。
I've been following package by feature structure for grouping my classes, and this is basically the structure I have: 我一直按照功能结构对包进行分组,以便对我的类进行分组,这基本上就是我所拥有的结构:
- data
- local
- model
- LocalModel.java
- remote
- model
- RemoteModel.java
- ui
- features
Both models contains exactly the same attributes, ie: 两种模型都包含完全相同的属性,即:
RemoteModel.java RemoteModel.java
public class RemoteModel implements Parcelable {
private String name; //has getter and setter
...
}
LocalModel.java LocalModel.java
public class LocalModel implements Parcelable {
private String name; //has getter and setter
...
}
Under the features package, I have an Activity for showing up the details of the models. 在功能包下,我有一个活动,用于显示模型的详细信息。 The thing is, that the Activity can be started holding either a RemoteModel or a LocalModel object. 事实是,可以启动Activity来保存RemoteModel或LocalModel对象。 But, as part of the attributes of that Activity it just has an RemoteModel attr, as follow: 但是,作为该Activity属性的一部分,它只有一个RemoteModel属性,如下所示:
public class DetailsActivity extends AppCompartActivity {
...
private TextView mName;
private RemoteModel mRemoteModel;
...
public void onCreate(Bundle savedInstanceState) {
...
mRemoteModel = getIntent().getExtras().getParcelable(EXTRA_RESULT_TITLE);
...
mName.setText(mRemoteModel.getName());
}
}
That way it works fine until I run the app, and tap on view details button then the following beatiful error appears: 这样,在我运行应用程序之前,它可以正常工作,然后点击“查看详细信息”按钮,然后出现以下美丽错误:
java.lang.ClassCastException: com.carlosparra.myApp.data.local.model.LocalModel cannot be cast to com.carlosparra.moviestvtracker.moviesandtvshowstracker.data.remote.model.RemoteModel
I know what the error means, so that's why I'm wondering how can I map those two classes from different data sources in an shared object that I can pass it to the details Activity. 我知道错误的含义,所以这就是为什么我想知道如何将共享对象中来自不同数据源的这两个类映射到共享对象中,然后将其传递给详细信息Activity。
You can define the necessary getters and setters in the interface Parcelable
: 您可以定义在接口必要的getter和setter Parcelable
:
public interface Parcelable {
String getName();
}
Then, instead of getting a RemoteModel
in the activity, you get a Parcelable
object: 然后,您将获得一个Parcelable
对象,而不是在活动中获得RemoteModel
:
public class DetailsActivity extends AppCompartActivity {
...
private TextView mName;
private Parcelable mParcelable;
...
public void onCreate(Bundle savedInstanceState) {
...
mParcelable = getIntent().getExtras().getParcelable(EXTRA_RESULT_TITLE);
...
mName.setText(mParcelable.getName());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.