2011-03-07 2 views
0

나는 스피너와 확인 버튼이있는 대화 상자가 있습니다. 나는 또한 스피너에서 항목을 선택하는 사용자에 의해 채워지는 arraylist를 가지고있다. 응용 프로그램에서 arraylist를 파일로 저장하고 모든 실행시로드하려고합니다. (왜냐하면 arraylist를 저장하지 않으면 시작할 때 항상 비어 있기 때문입니다.)Android 파일 쓰기, 읽기

그래서 여기에 제가 사용하고있는 코드가 있습니다. 저축은 괜찮을거야, 적어도 나는 Saving OK라는 토스트 메시지를 받는다. 사용자가 [확인]을 클릭 할 때이 코드는 OKbtn 리스너 때문에, 항목은 ArrayList에 추가됩니다되며,이 코드가 온다 :

if (assignArr.size() > 0) 
         { 
         String filename = "file.txt"; 
         ArrayList<String> report = new ArrayList<String>(); 

         for (int i=0; i<assignArr.size(); i++) 
         { 
          report.add(assignArr.get(i)); 
         } 

           FileOutputStream fos; 
               try { 
                 fos = openFileOutput(filename,Context.MODE_PRIVATE); 
             ObjectOutputStream out = new ObjectOutputStream(fos); 
             out.writeObject(report); 
             out.close(); 
             Toast.makeText(MainActivity.this, "Saving OK", Toast.LENGTH_LONG).show(); 
               } catch (FileNotFoundException e) { 
                 // TODO Auto-generated catch block 
                 e.printStackTrace(); 
               } catch (IOException e) { 
                 // TODO Auto-generated catch block 
                 e.printStackTrace(); 
               } 
         } 

내가 코드의 시작 부분에 로딩 부분을 넣어,하지만 난 생각하지 않는다 중요한 사항 :

words = new ArrayList<String>(50); 
     try { 
     InputStream is = getResources().getAssets().open("file.txt"); 

     BufferedReader br = new BufferedReader(new InputStreamReader(is)); 
     String line; 

     while((line = br.readLine()) != null) 
     { 
       words.add(line); 
     } 
     is.close(); 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 

     if (words.size() > 0) 
     { 
      for (int i=0; i<words.size(); i++) 
      { 
       assignArr.add(words.get(i)); 
       Toast.makeText(MainActivity.this, "Loading OK", Toast.LENGTH_LONG).show(); 
      } 
     } 

이 경우에는 축배 메시지를받지 못합니다. 파일을 만드는 위치가 한 가지 문제 일 수 있습니다. 에뮬레이터와 전화는 어디에 있습니까? 그리고 전화에 관해서는, 그것은 SD 카드 또는 전화 메모리에 생성됩니까? arraylist를 저장하고로드하는 데 올바른 코드가되기를 바랍니다. 코드에 어떤 문제가 있습니까?

업데이트 : InputStream is = getResources().getAssets().open("file.txt");InputStream is = openFileInput("file.txt"); 으로 바 꾸었습니다. 저축과 적재 결과를 이상한 메시지 인 쓸데없는 메시지로 씁니다 :

Toast.makeText(MainActivity.this, "Saving OK + " + report, Toast.LENGTH_LONG).show(); 

보십시오. 바닥에있는 단어는 부분적으로 헝가리 이름입니다. 그래서 파일에 arraylist를 저장하는 것이 문제 일 수 있습니다.

enter image description here

+0

여기를 찾아보고 http://stackoverflow.com/questions/17650522/write-in-file-and-read-it-and-put-on-in-a--speed-in-android 행운을 빕니다. –

답변

0

당신이 openFileOutput을 통해 생성 한 파일은 Context#getFilesDir()를 사용하여 얻을 수있는 앱의 개인 디렉토리에 기록됩니다 (보통은 /data/data/<your-app-package>/있어).

이 디렉토리는 assets 폴더와 아무 관련이 없습니다.