this file saves (date,time, voice input newline()) im wondering how to process this file into the textview so it reads it from the bottom to the top so i can put the most recent at the top of the textview, thankyou for your time
wi =(TextView)findViewById(R.id.hes);
try {
BufferedReader inputReader = new BufferedReader(new FileReader("/data/data/jip.lam.ru/file"));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
stringBuffer.append(inputString + "\n");
}
wi.setText(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
You can implement a Stack.
String inputString;
Stack<String> readbuffer =new Stack<String>();
while ((inputString = inputReader.readLine()) != null)
{
readbuffer.push(inputString);
}
Now pop the Stack i.e
wi.setText(readbuffer.pop());
Related
I want to work with a text in android studio that is very long(70 pages approximately). first is a way to put in my main activity in android studio code?
OR how can I import it and use it as string?
for example:
String deey = "my long text";
so I cant use it. I want to add it to my program and use it as string.
I put it into asset folder. but I can't use it.
You can get an InputStream from the AssetManager calling the opne() method.
public static String getReadTextFromAssets(Context context, String textFileName) {
String text;
StringBuilder stringBuilder = new StringBuilder();
InputStream inputStream;
try {
inputStream = context.getAssets().open(textFileName);
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
while ((text = bufferedReader.readLine()) != null) {
stringBuilder.append(text);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
Keep your file in the assets folder.
Put it in assets and read it using the below function.
public String readFromAssets(String fileName, Context context) {
StringBuilder returnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets()
.open(fileName, Context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
returnString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return returnString.toString();
}
So in your code you will initialise the string as
String longString = readFromAssets("helloworld.txt",mContext);
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();
}
my app requires that texts be saved(user choice) into the internal memory and then i want something like a favorite feature where user clicks on a button and a favorite activity starts to load the files saved in the memory(internal). in my program there are multiple texts and i have used a random generator to save the files as "fav1" "fav2" etc.. where the integer part is generated randomly. the problem is that now i don't know how to give my file name so that the files are retrieved and shown in a text View.
public void load(String name){
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput(filename)));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
stringBuffer.append(inputString + "\n");
}
show.setText(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
so how do you suggest i retrieve the files, its getting frustrating anyone help.
you can do it easily by the following code;
as you said it reads from file from internal storage.
private String readFromFile(String fname) {
String ret = "";
try {
InputStream inputStream = openFileInput(fname+".txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
show.setText(stringBuilder.toString());
inputStream.close();
}
}
EDIT
to read from the path contains path seperators
File myFile = new File(fname+".txt"); // path contains full path to the file including file name
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = myReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
show.setText(stringBuilder.toString());
myReader.close();
EDIT 2
to list files from specific directory and to choose the required file by its name.
File directory = new File(Environment.getExternalStorageDirectory()+"/sample");
// check the existance of the parent directory
if (directory.exists()) {
// get the list of files from the directory and keep it in an array of type File.
File[] fileList = directory.listFiles();
for (File file : fileList) {
//compares with filename: you can change this to your required file!
if (file.getName().equals("sam2.txt")) {
// method to read and show the text in text view
loadFile(file);
}
}
finally the definition of loadFile() method:
private void loadFile(File file) {
// TODO Auto-generated method stub
FileInputStream fIn;
try {
fIn = new FileInputStream(file);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = myReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
show.setText(stringBuilder.toString());
myReader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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();
}
I want to read several lines from a text file. These line should be displayed one by one, when I click the next button. I am able to store the strings in a file and read the first line. But when I try to read the next line using the next button, it stops working. Can anybody tell me a solution for this. Thanks in advance.
I have defined the following,
BufferedReader buffreader;
String line;
String fav;
StringBuilder text;
InputStream instream;
String favQuote0;
This is in my oncreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
StringBuilder text = new StringBuilder();
try {
// open the file for reading
InputStream instream = openFileInput("myfilename.txt");
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
fav = text.toString();
}
}
} catch (IOException e) {}
TextView tv1 = (TextView)findViewById(R.id.textView2);
tv1.setText(fav);
}
This is my next button
public void next (View view1) {
try {
// open the file for reading
InputStream instream = openFileInput("myfilename.txt");
// if file the available for reading
if (instream != null) {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
fav = text.toString();
}
}
} catch (IOException e) {}
TextView tv1 = (TextView)findViewById(R.id.textView2);
tv1.setText(fav);
}
Both answers do it the wrong way. I will post a description below my code. This is the proper way of doing it.
private int mCurrentLine;
private ArrayList<String> mLines;
private TextView mTextView;
private Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
mCurrentLine = -1;
mLines = new ArrayList<String>();
mTextView = (TextView) findViewById(R.id.text_view);
mButton = (Button) findViewById(R.id.button);
try {
readLinesAndSaveToArrayList();
}
catch (IOException e) {
e.printStackTrace();
}
setTextAndIncrement();
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setTextAndIncrement();
}
});
}
private void readLinesAndSaveToArrayList() throws IOException {
File file = new File("myfilename.txt");
if (!file.exists()) {
throw new FileNotFoundException("myfilename.txt was unable to locate");
}
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
mLines.add(line);
}
bufferedReader.close();
}
private void setTextAndIncrement() {
if (mCurrentLine == mLines.size() - 1) {
return;
}
mCurrentLine++;
mTextView.setText(mLines.get(mCurrentLine));
}
What I do is cache the file's contents in a scalable ArrayList. Each line will be assigned to an index in the array, eg. 0, 1, 2 and so on.
mCurrentLine takes care of positioning in the array. It starts at -1 because there is no current line. In the setTextAndIncrement() it will be set to 0, which in the array is the first index (the first line). The continuous calls will increment the position and take the next lines. If you come to the limit I have put in a check that looks if the mCurrentLine is equal to the max size of lines (mLines.size() - 1, a - 1 because arrays starts from 0 instead of 1).
Other than that I would advice you to use full length names on methods and variables; there is no need to keep them short, it will only make reading them harder. XML should also only contain low letters instead of camelCases.
Try this. This i working for me
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuffer bf = new StringBuffer();
String json = reader.readLine();
try {
do {
bf.append(json);
json = reader.readLine();
}while (json != null);
wt.flush();
wt.close();
Log.d("LOG", " read line output "+new String(bf)+" json "+json);
reader.close();
} catch (Exception e) {
e.printStackTrace(); }
wt is the bufferedwriter which i used to write line. I read from reader and write into file stored locally.
try {
// open the file for reading
InputStream instream = new FileInputStream("myfilename.txt");
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (buffreader.hasNext()) {
line = buffreader.readLine();
// do something with the line
}
}
} catch (Exception ex) {
// print stack trace.
} finally {
// close the file.
instream.close();
}