【发布时间】:2017-07-16 14:34:13
【问题描述】:
我正在从 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 设置为状态时返回单个项目,否则当我将PrimaryKey 设置为id 时它返回多个重复数据。我不确定我可能错在哪里。
【问题讨论】:
-
您是否从androidhive.info/2016/05/… 收到
RealmController?因为如果是这样,你应该把它从你的项目中删除,不要回头。 -
@EpicPandaForce 那么你有什么建议呢?问题是我在我的 json 中有重复的项目我如何将它们解析为单个对象请在此处查看:pastebin.com/VcQkVTHt
-
id中的Record字段应使用@PrimaryKey注释 -
@EpicPandaForce 同一市场的 id 不同,仍会返回多个相同价值的对象,对吧?
-
我不明白这个问题