我正在从 json api 获取数据,我已将 PrimaryKey
设置为状态。这是我正在获取的 Json
数据:
records[
{
"id":"192693681",
"timestamp":"1500204608",
"state":"Rajasthan",
"district":"Rajasamand",
"market":"Rajasamand",
"commodity":"Sugar",
"variety":"Shakkar",
"arrival_date":"16/07/2017",
"min_price":"4000",
"max_price":"4100",
"modal_price":"4050"
},
{
"id":"192693701",
"timestamp":"1500204608",
"state":"Rajasthan",
"district":"Rajasamand",
"market":"Rajasamand",
"commodity":"Wheat",
"variety":"Farmi",
"arrival_date":"16/07/2017",
"min_price":"1600",
"max_price":"1650",
"modal_price":"1625"
},
{
"id":"192693721",
"timestamp":"1500204608",
"state":"Rajasthan",
"district":"Rajasamand",
"market":"Rajasamand",
"commodity":"Wheat",
"variety":"Lokwan",
"arrival_date":"16/07/2017",
"min_price":"1550",
"max_price":"1600",
"modal_price":"1575"
}
]
这是我返回每个州的市场数据的查询:
private void populateMarketData(String state){
cityAdapter = new CityAdapter(mRealm.where(Records.class).equalTo(Constants.STATE, state).findAll(), this);
cityRecyclerView.setAdapter(cityAdapter);
Log.d(TAG, "Total Cities" + String.valueOf(cityAdapter.getData().size()));
cityAdapter.notifyDataSetChanged();
}
这是我的查询,用于返回具有以下状态的市场的所有商品:
@Override
public void onMarketClicked(String cityName) {
tradeAdapter = new TradeAdapter(mRealm.where(Records.class)
.equalTo(Constants.MARKET, cityName).findAll(), this);
tradeRecyclerView.setAdapter(tradeAdapter);
}
这是GcmTaskService
,用于更新后台服务中的数据:
Realm.init(mContext);
List<Records> records = new MandiDataHandler().getMandiQuotes(url);
SaveMandi saveMandi = new SaveMandi(state, records);
Realm realm = new RealmController(getApplication()).getRealm();
realm.beginTransaction();
realm.copyToRealmOrUpdate(saveMandi);
realm.commitTransaction();
realm.close();
这是DataHelper
,用于保存来自Json
API的数据
@PrimaryKey
private String state;
private RealmList<Records> recordsRealmList = new RealmList<>();
public SaveMandi(){}
public SaveMandi(String state, List<Records> recordsList) {
try {
this.state = state;
for (Records records: recordsList ) {
records = new Records(records.getId(), DateUtils.getRelativeTimeSpanString(
Long.parseLong(records.getTimestamp())).toString(), records.getState(), records.getMarket(),
records.getCommodity(), records.getVariety(), records.getMin_price(), records.getMax_price());
this.recordsRealmList.add(records);
}
}catch (Exception e){
e.printStackTrace();
}
}
我的RealmRecyclerView
中的问题是,当我将PrimaryKey
设置为state时,它返回单个项目,否则当我将PrimaryKey
设置为id时,它返回单个项目它返回多个重复数据。我不确定我哪里可能错了。
最佳答案
您想选择您的PrimaryKey
只有当它们(你认为)“相等”时才会匹配,就像 equals()
方法。如果你放两个 RealmObjects
与相同的PrimaryKey
进入 Realm 后,只有其中一个会出现在 Realm 中,因为每个不同的对象只能有一个 PrimaryKey
.
例如,如果我有 RealmObject a
与 PrimaryKey
的1
在 Realm 中,我又放了另一个 RealmObject b
与 PrimaryKey
的1
进入 Realm ,a
将被删除 b
因为每个 PrimaryKey
只能有一个对象.
查看 Realm 数据库的一个好工具是 Stetho ,我强烈推荐使用 Realm 来调试应用程序。
关于java - Realm RecyclerAdapter 返回单个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45129732/