2016-05-13 8 views
-1

fileからテキストを取得し、textViewに適用しようとしています。しかし、私はfile pathと返されています。txtファイルを読み込んで、異なるフラグメント/アクティビティのtextViewに表示する

@Override 
public void onViewCreated(View view, Bundle savedInstanceState){ 
    tv = (TextView) getActivity().findViewById(R.id.clockText); 
    // Displaying the user details on the screen 
    try { 
     getFileText(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 


public void getFileText() throws IOException { 
    File path = getActivity().getExternalFilesDir(null); //sd card 
    File file = new File(path, "alarmString.txt"); //saves in Android/ 
    FileInputStream stream = new FileInputStream(file); 
    try{ 
     stream.read(); 
     tv.setText(file.toString()); 
    } finally { 
     stream.close(); 
    } 
} 

結果ではなく、時間の"Android/data/foldername/example/files/alarmString.txt"は、例えば、異なる活動にユーザによって宣言されている:18:05

答えて

0

あなたはgetFileText関数から文字列を返すし、テキストビューにその文字列を設定する必要が従って

@Override 
public void onViewCreated(View view, Bundle savedInstanceState){ 
    tv = (TextView) getActivity().findViewById(R.id.clockText); 
    // Displaying the user details on the screen 
    try { 
     tv.setText(getFileText()); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 


public String getFileText() throws IOException { 
    File path = getActivity().getExternalFilesDir(null); //sd card 
    File file = new File(path, "alarmString.txt"); //saves in Android/ 
    BufferedReader br = new BufferedReader(new FileReader(file)); 
try { 
    StringBuilder sb = new StringBuilder(); 
    String line = br.readLine(); 

    while (line != null) { 
     sb.append(line); 
     sb.append(System.lineSeparator()); 
     line = br.readLine(); 
    } 

} finally { 
    br.close(); 
} 
return sb.toString() 
} 

としてそれを行います。

0

ファイルパスを返すfile.toStringを設定しています。ファイルに存在するデータを設定したい場合は、ストリームを読み込んでwhileループ内でstringbufferに追加し、テキストがファイルに取り込まれ、最後にstringbuffer.toStringをtextviewに設定する必要があります。

1
public String getFileContent(File file) throws IOException { 
    String str = ""; 
    BufferedReader bf = null; 
    try { 
     bf = new BufferedReader(new FileReader(file)); 
     while(bf.ready()) 
      str += bf.readLine(); 
    } catch (FileNotFoundException e){ 
     Log.d("FileNotFound", "Couldn't find the File"); 
    } finally { 
     bf.close(); 
    } 
    return str; 
} 

バイトを読み取る代わりに、BufferedReaderとFileReaderを使用します。使用したのは

stream.read();

あなたのファイルの1バイトが得られます。

tv.setText(file.toString());

は、ファイルの内容ではなくfile.toString()メソッドの出力にTextViewを設定します。

関連する問題