我想使用 protocoll-buffers 加载一些数据(JSON 在 Android 上太慢了),但不知何故,我的repeated
字段company
包含每个元素的 6 个副本 - 尽管我没有存储任何重复项。
我怎么知道它不应该包含重复项?
我确实为我保存的每个对象设置了一个计数器 - 这是预期的长度。
这是我的架构:
syntax = "proto3";
[...]
message CompanyProtoRepository {
// THIS FIELD CONTAINS DUPLICATES!
repeated CompanyProto company = 1;
}
我如何存储我的数据:
public void writeToFile(String fileName) {
CompanyProtos.CompanyProtoRepository repo = loadRepository();
try {
OutputStream outputStream = mContext.openFileOutput(fileName, Context.MODE_PRIVATE);
repo.writeTo(outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
private CompanyProtos.CompanyProtoRepository loadRepository() {
CompanyLoaderService jsonLoader = new JsonCompanyLoaderService(mContext.getResources());
CompanyProtos.CompanyProtoRepositoryOrBuilder repo = CompanyProtos.CompanyProtoRepository.newBuilder();
int counter = 0; // Will be 175 which is correct (every company 1 time)
// Will contain every id only time -> correct!
HashMap<Integer, Integer> map = new HashMap<>();
for (Company company : jsonLoader.getCompanies()) {
counter++;
if (!map.containsKey(company.getName()))
map.put(company.getId(), 1);
else
map.put(company.getId(), map.get(company.getId()) + 1);
CompanyProtos.CompanyProto proto = toProto(company);
if (!repo.getCompanyList().contains(proto))
((CompanyProtos.CompanyProtoRepository.Builder) repo).addCompany(proto);
}
return ((CompanyProtos.CompanyProtoRepository.Builder) repo).build();
}
这就是我加载数据的方式:
private List<Company> loadCompanies() {
CompanyProtos.CompanyProtoRepository repo = null;
try {
InputStream inputStream = mContext.getResources().openRawResource(R.raw.company_buffers);
repo = CompanyProtos.CompanyProtoRepository.parseFrom(inputStream);
ArrayList<Company> list = new ArrayList<>();
for (CompanyProtos.CompanyProto companyProto: repo.getCompanyList()) {
list.add(fromProto(companyProto));
}
// This list contains every company 6 times!
return list;
} catch (Exception ex) { }
}
当然,我希望每家公司只有 1 次,因为我确认每家公司只存储一次CompanyProtoRepository
而不是 6 次。