How to load text from file to textview [duplicate] - android

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
android reading from a text file
So I need to load text, but I don't know how :( To save text I'm doing this
File logFile = new File("sdcard/data/agenda.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(editText1.getText());
buf.newLine();
buf.close();
}
catch (IOException e)
{
e.printStackTrace();
}
So, how to load it back by button tap?

To read content of file, for example *.txt - do this...
private String GetPhoneAddress() {
File file = new File(Environment.getExternalStorageDirectory() + "/reklama/tck.txt");
if (!file.exists()){
String line = "Need to add smth";
return line;
}
String line = null;
//Read text from file
//StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
line = br.readLine();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
return line;
}
Then, from activite to set to textview - just do smthing like
final TextView tvphone = (TextView) findViewById(R.id.saved_phone);
String saved_phone = GetPhoneAddress();
if (saved_phone.length()>0){
tvphone.setText(saved_phone);
}

This function will read your whole file, and set it to the parameter TextView as text, if this is what you want. Your code is trying to write the TextViews content to a file, it's not reading it.
public void loadToTextView(TextView textView) throws Exception
{
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(path, "filename.file");
textView.setText(new Scanner(file).useDelimiter("\\Z").next());
}
Be careful, you will need to handle the Exception, that this function might throw.

This method will read each line into a StringBuffer.
Then just call setText(contentsOfFile) on your TextView.
BufferedReader fileReader = new BufferedReader(new FileReader("/mnt/sdcard/agenda.file"));
StringBuilder strBuilder = new StringBuilder();
String line;
while((line = fileReader.readLine()) != null)
{
strBuilder.append(line);
}
fileReader.close();
strBuilder.trimToSize();
String contentsOfFile = strBuilder.toString();

Related

Ifstream won't open file C++ with JNA Android Studio

I am trying to read in a file using the fstream. I am writing in C++11, but interfacing it with Java via JNI in Android Studio. It doesn't open the file for some reason. I am using a relative file path and I don't understand why it can't open the file. The file is named proverbs.txt. There aren't any discrepancies within the name like proverbs.txt.txt or anything like that.
Here's the code:
void storeProverbs() {
string path = "/Users/tenealaspencer/Desktop/proverbs.txt";
std::ifstream provInput(path.c_str(), std::ios::in);
//provInput.open("/Users/tenealaspencer/Desktop/proverbs.txt");
// opens the proverbs text file
equivInput.open("/Users/tenealaspencer/AndroidStudioProjects/example/app/src/main/cpp/stored.txt"); // opens the stored (English) proverbs text file
if (!provInput.is_open()) {
cout << "error ";
}
while (!provInput.eof()) // while not at the end of the proverbs file
{
getline(provInput, phrase); // read proverbs in line by line
getline(equivInput, storedProv); // read english proverbs in line by line
Never mind I just imported the file via Java using the following code:
try {
InputStream is = getAssets().open("stopwords.txt");
String line1;
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while((line1 = reader.readLine()) != null) //
{
try {
byte[] utf8Bytes = line1.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
storeStopWords(line1);
}
}
catch (IOException e) {
e.printStackTrace();
}
try {
InputStream is = getAssets().open("proverbs.txt");
InputStream iz = getAssets().open("stored.txt");
String line;
String line2; //= new String ("");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
BufferedReader reader2 = new BufferedReader(new InputStreamReader(iz));
while((line = reader.readLine()) != null && (line2 = reader2.readLine()) != null ) //
{
try {
byte[] utf8Bytes = line.getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
storeProverbs(line,line2);
}
}
catch (IOException e) {
e.printStackTrace();
}
I read somewhere that JNA doesn't support the fstream library or something like that. In any case it works.

How to set default open with(dialog) option to my android app?

I have a file in my devise called test.csv. when i click on that file is opened through my app.how to set default open with(dialog) option to my app in android?
above is the sample dailog.how to add my app to the dialog list?
I think you may want to read the csv file. you could get the csv file path. So see the following.
public static void readCSV(File file) {
BufferedReader reader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file));// your csv file
reader = new BufferedReader(isr);
String line = null; // every time read one line
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The stringBuilder.toString() is your csv file's content. Sorry for my English.

How to read XML file and pass to setText as String with all tags and white-characters [Android]

I want to read XML file, save it as String and pass to setText. I don't want to parse it but see it on my smartphone screen with all tags and white-characters, eg.
<a>
<b>some text</b>
</a>
not:
some text
How to do it?
FYI, this is how I solve my problem:
public String readXML() {
String line;
StringBuilder total = new StringBuilder();
try {
InputStream is = activity.getAssets().open("subjects.xml");
BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8"));
total = new StringBuilder();
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
return total.toString();
}
Use FileInputStream to read file:
File file = new File(<FilePath>);
if (!file.exists()) {
System.out.println("File does not exist.");
return;
}
if (!(file.isFile() && file.canRead())) {
System.out.println(file.getName() + " cannot be read from.");
return;
}
try {
FileInputStream stream = new FileInputStream(file);
char current;
while (stream.available() > 0) {
current = (char) stream.read();
//Do something with character
}
} catch (IOException e) {
e.printStackTrace();
}

Android how i can display the text file from sd card and display the text one by one

I have a text file on my sd card which contains the following data:
Farhan shah
Noman Shah
Ahmad shah
Mohsin shah
Haris shah
I have one TextView into my app,now I want when I run my app,my TextView display just the 1st name "Farhan Shah", and after x seconds it's display "Noman Shah" and so on..
but now when I run my app it reads all the text and display in my textview.
any help will be highly appreciated,Thanks.
This is my code:
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"test.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
e.printStackTrace();
}
t = new TextView(this);
t = (TextView) findViewById(R.id.tv_textlist);
t.setText(text);
This happens because you read in the whole file into text before you set your textview to it's content.
try it like this:
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"test.txt");
//Read text from file
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
TextView t = (TextView) findViewById(R.id.tv_textlist);
Timer mTimer = new Timer();
TimerTask Next = new TimerTask() {
#Override
public void run() {
try {
String line = br.readLine();
if(line!= null)
t.setText(line);
else
mTimer.cancel();
} catch (IOException e) {
}
}
};
mTimer.scheduleAtFixedRate(Next,100L,TimeXinMillis);
Instead of text.append('\n'); add some delimiter like text.append('|');
later split it into a string array and loop through
t = (TextView) findViewById(R.id.tv_textlist);
text.append('|');
String[] splitText = text.toString().split("|");
for(int i = 0; i < splitText.length; i++) {
t.setText(splitText[i]);
}
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
textnames.add(line);
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
e.printStackTrace();
}

Writing/Reading Files to/from Android phone's internal memory

I have an utility class named 'MyClass'. The class has two methods to read/write some data into phone's internal memory. I am new to android, Please follow below code.
public class MyClass {
public void ConfWrite() {
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir()+File.separator+"MyFile.txt")));
bufferedWriter.write("lalit poptani");
bufferedWriter.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
while executing ConfWrite method, it fails
please provide a better solution to solve this
thanks in advance
You can Read/ Write your File in data/data/package_name/files Folder by,
To Write
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir()+File.separator+"MyFile.txt")));
bufferedWriter.write("lalit poptani");
bufferedWriter.close();
To Read
BufferedReader bufferedReader = new BufferedReader(new FileReader(new
File(getFilesDir()+File.separator+"MyFile.txt")));
String read;
StringBuilder builder = new StringBuilder("");
while((read = bufferedReader.readLine()) != null){
builder.append(read);
}
Log.d("Output", builder.toString());
bufferedReader.close();
public static void WriteFile(String strWrite) {
String strFileName = "Agilanbu.txt"; // file name
File myFile = new File("sdcard/Agilanbu"); // file path
if (!myFile.exists()) { // directory is exist or not
myFile.mkdirs(); // if not create new
Log.e("DataStoreSD 0 ", myFile.toString());
} else {
myFile = new File("sdcard/Agilanbu");
Log.e("DataStoreSD 1 ", myFile.toString());
}
try {
File Notefile = new File(myFile, strFileName);
FileWriter writer = new FileWriter(Notefile); // set file path & name to write
writer.append("\n" + strWrite + "\n"); // write string
writer.flush();
writer.close();
Log.e("DataStoreSD 2 ", myFile.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readfile(File myFile, String strFileName) {
String line = null;
try {
FileInputStream fileInputStream = new FileInputStream(new File(myFile + "/" + strFileName)); // set file path & name to read
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // create input steam reader
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) { // read line by line
stringBuilder.append(line + System.getProperty("line.separator")); // append the readed text line by line
}
fileInputStream.close();
line = stringBuilder.toString(); // finially the whole date into an single string
bufferedReader.close();
Log.e("DataStoreSD 3.1 ", line);
} catch (FileNotFoundException ex) {
Log.e("DataStoreSD 3.2 ", ex.getMessage());
} catch (IOException ex) {
Log.e("DataStoreSD 3.3 ", ex.getMessage());
}
return line;
}
use this code to write --- WriteFile(json); // json is a string type
use this code to read --- File myFile = new File("sdcard/Agilanbu");
String strObj = readfile(myFile, "Agilanbu.txt");
// you can put it in seperate class and just call it where ever you need.(for that only its in static)
// happie coding :)

Categories

Resources