jeudi 31 mars 2016

Nested ArrayList and manual database entry

I'm working on a RecyclerView in Android that looks like this:

A

A topic1

A topic2

A topic3

B

B topic1

B topic2

With the topics hidden until you tap on the parent letter.

I've got something that I think should be working, but now if I add rows to my database manually (which is by design), additional rows aren't recognized, even if I uninstall the app and load it back in. This is what I'm looking at:

final List<AToZList> aToZ = addTopics();
mAdapter = new AToZAdapter(getContext(), aToZ);

...

private List<AToZList> addTopics() {
        topics = new ArrayList<Topic>();
        List<AToZList> aToZ;
        AToZList A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z;
        A=B=C=D=E=F=G=H=I=J=K=L=M=N=O=P=Q=R=S=T=U=V=W=X=Y=Z = null;

        Cursor topicCursor = database.rawQuery("SELECT " + ExternalDbContract.QuoteEntry.TOPIC +
                " FROM " + ExternalDbContract.QuoteEntry.TABLE_NAME, null);

        try {
            for (topicCursor.moveToFirst(); !topicCursor.isAfterLast(); topicCursor.moveToNext()) {
                String firstLetter = topicCursor.getString(0).toUpperCase().substring(0, 1);

                switch (firstLetter) {
                    case "A":
                        if(A == null) {
                            A = new AToZList("A", getTopics(firstLetter));
                        }
                        break; //and so on for every letter
                }finally {
                    aToZ = Arrays.asList(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z);
                }
    topicCursor.close();
    return aToZ;

...

private ArrayList<Topic> getTopics(String firstLetter) {
        Cursor topicCursor = database.rawQuery("SELECT " + ExternalDbContract.QuoteEntry.TOPIC +
                " FROM " + ExternalDbContract.QuoteEntry.TABLE_NAME, null);

        ArrayList<Topic> topicsByLetter = new ArrayList<Topic>();

        for(topicCursor.moveToFirst(); !topicCursor.isAfterLast(); topicCursor.moveToNext()) {
            if (topicCursor.getString(0).toUpperCase().substring(0, 1).equals(firstLetter)) {
                topicsByLetter.add(new Topic(topicCursor.getString(0)));
            }
        }
        topicCursor.close();
        return topicsByLetter;
    }

That's a lot of code.

I've added some logging to see what's actually getting passed through. I have 3 topic entries in the database, two that start with "A" and a third that starts with "B". The A's come through okay (there are two entries for that), and then for some reason it kicks out to the finally block, and ruins the Array because it only has one entry (as in, one "A" entry). topicCursor.getCount() tells me that there are only two entries, but there are three. CURSE YOU CURSOR!

If it would be helpful I've committed where I'm at onto Github.

Aucun commentaire:

Enregistrer un commentaire