전편에 이어서 이제부턴 code 부연 설명 및 추가 code !!

전편 못 본분 여기!!
2012/02/08 - [Android Study] - Android List에 index를 표시해보자 2편



private Cursor bundleLetterCountExtras(Cursor cursor, final SQLiteDatabase db,
        SQLiteQueryBuilder qb, String selection, String[] selectionArgs, String sortOrder) {
    String sortKey;
    String sortOrderSuffix = "";

    // Sortkey 설정 부분 - 전낸 중요함 왜 냐면 index 뽑을 때 소트키로 뽑음 그러므로 NULL 안댐
    if (sortOrder != null) {
        int spaceIndex = sortOrder.indexOf(' ');
        if (spaceIndex != -1) {
            sortKey = sortOrder.substring(0, spaceIndex);
            sortOrderSuffix = sortOrder.substring(spaceIndex);
        } else {
            sortKey = sortOrder;
        }
    }

    // 실제 sortkey로 사용 될 부분 위에서 지정한 sortkey가 null 이면 안되는 이유가 여기임!!    
    String subSortKey = "SUBSTR(" + sortKey + ",1,1)";

    // 국가 세팅 얻어오기 (국가별로 sort 내용이 다르니까!!)
    String locale = getLocale().toString();

    // Projection list 만들기 (이거 좀 신기함, 내가 Android SQL은 안까봐서 모르겠는데...
    // 일케도 돌아가나 봄. (아니면 특별히 만든 내용일 확률이 99.9%이긴 한데...)
    HashMap projectionMap = new HashMap();

    // 빨간색 글귀 변경되면 안됨. SQL에서 따로 만들어 놓은 거라서 변경되면 안됨.
    // 변경되면 뭐랄까? 인식을 못 한다고나 할까? Error 날꺼임.. 
    // 추가로 google애들이 적어 놓은 주석을 알려주자면
    
    /**
     * Use the GET_PHONEBOOK_INDEX function, which is an android extension for SQLite3,
     * to map the first letter of the sort key to a character that is traditionally
     * used in phonebooks to represent that letter.  For example, in Korean it will
     * be the first consonant in the letter; for Japanese it will be Hiragana rather
     * than Katakana.
     */
    
     projectionMap.put(AddressBookIndexQuery.LETTER,
             subSortKey + " AS " + AddressBookIndexQuery.LETTER);
 
     projectionMap.put(AddressBookIndexQuery.TITLE,
            "GET_PHONEBOOK_INDEX(" + subSortKey + ",'" + locale + "')"
                    + " AS " + AddressBookIndexQuery.TITLE);

      projectionMap.put(AddressBookIndexQuery.COUNT,
            "COUNT(" + sortKey + ") AS " + AddressBookIndexQuery.COUNT);
 
     // Projection setting 해주기
      qb.setProjectionMap(projectionMap);

     // Query 돌리기!!
      Cursor indexCursor = qb.query(db, null, selection, selectionArgs,
            AddressBookIndexQuery.ORDER_BY, null /* having */,
            AddressBookIndexQuery.ORDER_BY + sortOrderSuffix);

      try {
          int groupCount = indexCursor.getCount();
          String titles[] = new String[groupCount];
          int counts[] = new int[groupCount];
          int indexCount = 0;
          String currentTitle = null;

          int count = 0;

         // 중복된 내용들은 정리하고 배열에 정리해 넣기
           for (int i = 0; i < groupCount; i++) {
              indexCursor.moveToNext();
              int latter = indexCursor.getInt(AddressBookIndexQuery.COLUMN_LETTER);
              String title = indexCursor.getString(AddressBookIndexQuery.COLUMN_TITLE);

              count = latter;
              if (indexCount == 0 || !TextUtils.equals(title, currentTitle)) {
               // titles 이게 index 글자들 배열
                  titles[indexCount] = currentTitle = title;
               // index의 position 배열 (2편에서 query 문에 의해 나온
               // bundleLetterCountExtras 여기 들어 오기전 cursor에서 position)
                  counts[indexCount] = count;
                  indexCount++;
              } else {
                counts[indexCount - 1] += count;
            }
        }

       // 배열 크기 조정
        if (indexCount < groupCount) {
            String[] newTitles = new String[indexCount];
            System.arraycopy(titles, 0, newTitles, 0, indexCount);
            titles = newTitles;

            int[] newCounts = new int[indexCount];
            System.arraycopy(counts, 0, newCounts, 0, indexCount);
            counts = newCounts;
        }

       // Bundle 형태로 담아서 cursor에 몰래 꼽아둠 ㅋㅋ
        final Bundle bundle = new Bundle();
       // 빨간색 부분은 Bundle 에서 Extra key 값임 알아서 처리 하셈
        bundle.putStringArray("님덜 맘대로", titles);
        bundle.putIntArray("님덜 맘대로", counts);
        return new CursorWrapper(cursor) {

            @Override
            public Bundle getExtras() {
                return bundle;
            }
        };
    } finally {
        indexCursor.close();
    }
}
으하하하 너무 길어서 담편에 부족한 code 추가 해야겠네...?
데헷~ 너무 좋다.
 


+ Recent posts