How to make Android Read txt file and setText or append to a TextView

r2sjoblom

New Member
Joined
Feb 24, 2011
Messages
10
Reaction score
0
Below is a sample from one of my class files that I am having problems with. What I really just want to do is to add a button to open a new Intent Activity with ACTION_VIEW to display the text file. This wasn't working inside the OnClickListener:

File file = new File(file://android_assets/browsercode.txt);Intent newintent = new Intent(android.conteent.Intent.ACTION_VIEW);
newintent.setData(file);
startActivity(newintent);

It just gave me an error. So instead i am going to just try to read the file's contents into a string and output it to a TextView. This wasn't working either. If anyone has any suggestion on either way, that would be greatful. I have tried many variations of each and got NOWHERE. I perfer the one above with the button click though.

Thanks in advance for any help.

public​
class CodeSlider extends Activity {
TextView
textcode;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.
codeslider);
textcode
= (TextView)findViewById(R.id.codetext);
readthefile();
}
privatevoid readthefile() {
//
TODO Auto-generated method stub
File file =​
new File(file://android_assets/browsercode.txt);
int i=0;
FileReader into =
null;
try
{into = new FileReader(file); // And a char stream to read it
char[] buffer = newchar[4096]; // Read 4K characters at a time
int len; // How many chars read each time
while ((len = into.read(buffer)) != -1){
String s =
new String(buffer, 0, len);
i++;

textcode
.append(s);
}
}
catch(IOException e) {
System.
out.println("Error");return;
}
}
}
 
OP
r2sjoblom

r2sjoblom

New Member
Joined
Feb 24, 2011
Messages
10
Reaction score
0
Got it!

I needed to use AssetManager API to import the stuff in the assets/ directory. Below is the code for anyone that needs it.

import​

java.io.IOException;

import​

java.io.InputStream;

import​

android.app.Activity;

import​

android.content.res.AssetManager;

import​

android.os.Bundle;

import​

android.widget.TextView;

public​

class CodeSlider extends Activity {
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.
codeslider);
TextView text = (TextView)findViewById(R.id.
codetext);
AssetManager am = CodeSlider.
this.getAssets();
int i=0;try {InputStream is = am.open("browsercode.txt");
byte
[] buffer = newbyte[4096]; // Read 4K characters at a time
int len; // How many chars read each time
while ((len = is.read(buffer)) != -1){
String s =
new String(buffer, 0, len);
text.append( s );
i++;

}
}
catch(IOException e) {
System.
out.println("Error");
return
;
}
}

}
 
Top