마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

txt 파일 저장에 대한 질문입니다.

0 추천

안녕하세요~! 제가 리스트뷰의 데이터들을 txt파일에 저장하는 예제를 공부하던 도중 문제점이 생겨

질문을 드립니다.

예를 들자면 txt파일에 1,2,3,4,5 의 내용이 나와야 하는데 5,5,5,5,5가 나오는 상황이 생겨 해결방법을 찾지 못해 도움을 요청하고자 글을 씁니다. 고수님들의 많은 조언 부탁드립니다! 해당 소스는 아래에 써 두었습니다.

 public boolean saveFile(Context context, String fileName) {

        // check if available and not read only
        if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
            Log.w("FileUtils", "Storage not available or read only");
            return false;
        }

        // Create a path where we will place our List of objects on external storage
        File file = new File(context.getExternalFilesDir(null), fileName);
        PrintStream p = null; // declare a print stream object

        boolean success = false;

        String item_content1 = cursor.getString(cursor.getColumnIndex(ClothAdapter.KEY_CONTENT1));
        String item_content2 = cursor.getString(cursor.getColumnIndex(ClothAdapter.KEY_CONTENT2));
        String item_content3 = cursor.getString(cursor.getColumnIndex(ClothAdapter.KEY_CONTENT3));
        String item_content4 = cursor.getString(cursor.getColumnIndex(ClothAdapter.KEY_CONTENT4));
        String item_content5 = cursor.getString(cursor.getColumnIndex(ClothAdapter.KEY_CONTENT5));

        try {
            OutputStream os = new FileOutputStream(file);
            // Connect print stream to the output stream
            p = new PrintStream(os);

            for (int i=0; i < cursor.getCount(); i++) {

                //p.println("Date : "+item_content1+" Product : "+item_content2+" Inproduct : "+item_content3+" Outproduct : "+item_content4+" Saveproduct : "+item_content5);

            }
            p.println(item_content1+" Product : "+item_content2+" Inproduct : "+item_content3+" Outproduct : "+item_content4+" Saveproduct : "+item_content5);

            Log.w("FileUtils", "Writing file" + file);
            success = true;
        } catch (IOException e) {
            Log.w("FileUtils", "Error writing " + file, e);
        } catch (Exception e) {
            Log.w("FileUtils", "Failed to save file", e);
        } finally {
            try {
                if (null != p)
                    p.close();
            } catch (Exception ex) {
            }
        }

        return success;
    }

 

KALECK (170 포인트) 님이 2017년 3월 1일 질문
println 전에 item_content1 ~ 5까지 로그는 찍어보셨어요?
디버깅 통해서 확인해보니까 생각했던대로 마지막으로 저장한 리스트 아이템 값들이 출력이 되는 것을 확인했는데 아이템 전체가 차례대로 나오게 하려면 어떻게 해야하는지 알려주실 수 있나요?

1개의 답변

0 추천

자답입니다. 항상 문제가 되는 것은 기초가 부족하다는 점이었다는 것을 이 문제를 통해 깨달았네요.

해결방법은 다음 링크를 통하여 해결하였습니다.(추가사항 : txt파일보다는 xls로 저장하는 것이 가독성에서 좋을 것 같아 방식을 변경하였습니다.)
http://devmas.tistory.com/entry/Cursor-%EC%82%AC%EC%9A%A9%EB%B2%95

http://www.mysamplecode.com/2011/10/apache-poi-excel-row-group-collapse.html

그리고 해결한 소스 결과를 첨부합니다.

Cursor cursor = myBusanClothAdapter.queueAll();
        cursor.moveToFirst();

        // Row and column indexes
        int idx = 0;

        if(cursor != null)
        {
            while(cursor.moveToNext()==true) {
                final int item_id = cursor.getInt(cursor.getColumnIndex(BusanClothAdapter.KEY_ID));
                String item_content1 = cursor.getString(cursor.getColumnIndex(BusanClothAdapter.KEY_CONTENT1));
                String item_content2 = cursor.getString(cursor.getColumnIndex(BusanClothAdapter.KEY_CONTENT2));
                String item_content3 = cursor.getString(cursor.getColumnIndex(BusanClothAdapter.KEY_CONTENT3));
                String item_content4 = cursor.getString(cursor.getColumnIndex(BusanClothAdapter.KEY_CONTENT4));
                String item_content5 = cursor.getString(cursor.getColumnIndex(BusanClothAdapter.KEY_CONTENT5));

//                for(int i = 1; i<cursor.getCount();i++) {
                    idx = idx+1;
                    Row rowdata = sheet1.createRow(idx);

                    c = rowdata.createCell(0);
                    c.setCellValue(item_content1);

                    c = rowdata.createCell(1);
                    c.setCellValue(item_content2);

                    c = rowdata.createCell(2);
                    c.setCellValue(item_content3);

                    c = rowdata.createCell(3);
                    c.setCellValue(item_content4);

                    c = rowdata.createCell(4);
                    c.setCellValue(item_content5);
//                }
                Log.i("커서 테스트",item_id+item_content1+item_content2+item_content3+item_content4+item_content5);

            }

        }

 

익명사용자 님이 2017년 3월 2일 답변
...