对使用realm.allObjects()感到困惑

时间:2015-08-21 00:31:33

标签: java android realm

我刚刚开始使用领域,我无法弄清楚如何获取数据库中的所有对象。我查看了文档,但我并没有完全理解它。以下是我到目前为止的情况:

mainFragment.java

static List<Acronym> realmResults;
Realm realmDB;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View layout = inflater.inflate(R.layout.fragment_acronyms_list, container, false);
    acronymList = (RecyclerView) layout.findViewById(R.id.acronymRecyclerView);
    addNewEntry = (Button) layout.findViewById(R.id.addBtn);

    realmDB = Realm.getInstance(getActivity());

    adapter = new acronymListAdapter(getActivity(), getData());
    acronymList.setAdapter(adapter);
    acronymList.setLayoutManager(new LinearLayoutManager(getActivity()));

    return layout;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    realmDB.beginTransaction();

    realmResults = realmDB.allObjects(RealmAcronym.class);

    realmDB.commitTransaction();

}

RealmAcronym.java

public class RealmAcronym extends RealmObject {
@PrimaryKey
private String          acronym;
private String          acronymFull;
private String          color;

@Ignore
private int             sessionId;

// Standard getters & setters generated by your IDE…
public String getAcronym() { return acronym; }
public void   setAcronym(String acronym) { this.acronym = acronym; }
public String getAcronymFull() { return acronymFull; }
public void   setAcronymFull(String acronymFull) { this.acronymFull = acronymFull; }
public String getColor() { return color; }
public void   setColor(String color) { this.color = color; }
public int    getSessionId() { return sessionId; }
public void   setSessionId(int dontPersist) { this.sessionId = sessionId; }

1 个答案:

答案 0 :(得分:2)

两件事:

  1. 您的结果应该以{{1​​}}类而不是RealmResults<RealmAcronym>结尾(以避免复制所有对象)。

  2. 只有在更改数据时才需要进行交易,而不仅仅是阅读。

    List