Reputation: 359
Im looping through a SDCard directory, reading the text in each file, and writing the text to dynamically added textViews. Each file contains line breaks, I think that it where the problem lies. I've searched SO, and Google, tried some suggestions, and now my code returns and prints each text file twice. The first only contains the text until the first line break, the ssecond prints the text exactly how I need it. Example text file test.txt
This is a test.
And I cannot make it work
The desired output is
test.txt
This is a test.
And I cannot make it work
The first time the views are added I get
test.txt
This is a test.
The second time, I get the desired output. It does this with all txt files
Here is my code
String sdcard = Environment.getExternalStorageDirectory() + "/.BELIEVE/PushMessages/";
// go to your directory
File fileList = new File( sdcard );
//check if dir is not null
if (fileList != null){
// so we can list all files
File[] filenames = fileList.listFiles();
// loop through each file
for (File tmpf : filenames){
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(tmpf));
String name = tmpf.getName();
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
TextView title = new TextView(PushMessagesPage.this);
TextView message = new TextView(PushMessagesPage.this);
ll.addView(title);
title.setLayoutParams(textViewParams);
title.setTextAppearance(this, android.R.attr.textAppearanceLarge);
title.setTextColor(0xff33b5e5);
title.setText(name);
ll.addView(message);
message.setLayoutParams(textViewParams);
message.setTextColor(0xffffffff);
message.setText(text);
What is wrong with this code?
Upvotes: 0
Views: 76
Reputation: 26034
Your code should be like this.
for (File tmpf : filenames) {
StringBuilder text = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(tmpf));
String name = tmpf.getName();
String line;
TextView title = new TextView(StackDemosActivity.this);
ll.addView(title);
title.setLayoutParams(textViewParams);
title.setTextAppearance(this,
android.R.attr.textAppearanceLarge);
title.setTextColor(0xff33b5e5);
title.setText(name);
TextView message = new TextView(StackDemosActivity.this);
ll.addView(message);
message.setLayoutParams(textViewParams);
message.setTextColor(0xffffffff);
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
message.setText(text);
} catch (Exception e) {
e.printStackTrace();
}
}
Upvotes: 1