How to read next line from a text file - android

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();
}

Related

How to read a .txt document line by line in android?

In this code, only the last word entered in the .txt file is being read. I am calling the same activity when a condition is met. What changes should I make to the code so that it reads a word, calls the same activity again and then reads a new word?
public class Page extends Activity {
Button b;
TextView t;
EditText e;
int i = 0;
String str2;
String w, x=null;
static BufferedReader c = null;
static BufferedReader ic = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page);
b = (Button) findViewById(R.id.benter);
t = (TextView) findViewById(R.id.tv);
e = (EditText) findViewById(R.id.et);
InputStream f = getResources().openRawResource(R.raw.incorrect);
ic = new BufferedReader(new InputStreamReader(f));
try {
while ((w = ic.readLine()) != null) {
t.setText(w);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
str2 = e.getText().toString();
if (str2.equals(x)) {
Toast.makeText(getApplication(), "RIGHT", Toast.LENGTH_LONG).show();
Intent open = new Intent(Page.this, Page.class);
startActivity(open);
} else {
Toast.makeText(getApplication(), "WRONG", Toast.LENGTH_LONG).show();
e.setText("");
}
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can read file line by line using this code
try {
FileReader fileReader = new FileReader("FilePath");
BufferedReader reader = new BufferedReader(fileReader);
String data = null;
StringBuilder builder = new StringBuilder();
while ((data = reader.readLine()) != null) {
builder.append(data);
}
System.out.println(builder.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In your code there is problem in your onclick listener .. please put onclick listener on out of while loop..
There is minot mistake in your onClickListener() :
public class Page extends Activity {
Button b;
TextView t;
EditText e;
int i = 0;
String str2;
String w, x=null;
static BufferedReader c = null;
static BufferedReader ic = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page);
b = (Button) findViewById(R.id.benter);
t = (TextView) findViewById(R.id.tv);
e = (EditText) findViewById(R.id.et);
InputStream f = getResources().openRawResource(R.raw.incorrect);
ic = new BufferedReader(new InputStreamReader(f));
try {
while ((w = ic.readLine()) != null) {
t.setText(w);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
str2 = e.getText().toString();
// it was str2.equals(x) nut x is null, replace w with x
if (str2.equals(w)) {
Toast.makeText(getApplication(), "RIGHT", Toast.LENGTH_LONG).show();
Intent open = new Intent(Page.this, Page.class);
startActivity(open);
} else {
Toast.makeText(getApplication(), "WRONG", Toast.LENGTH_LONG).show();
e.setText("");
}
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This code will work for you
You can use Apache Commons I/O library for this.It's so simple. And keep your code beauty. And why do get .txt files from assets ?
AssetManager am = context.getAssets();
InputStream fs = am.open("a.txt");
List<String> lines = IOUtils.readLines(file,"UTF-8");
You can save your text file in "Assets" folder of project and use following code to retrieve that file in java class
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("YOUR_TEXT_FILE.txt")));
StringBuilder total = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
total.append(line);
}
message=total.toString();
System.out.println(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
After that you have that file in String message
Your program is reading the last line because you are overwriting your 'w' variable every time that you are calling the readLine() method. What you should do is set your 'w' variable empty, and append it with readLine() to keep all the lines in your text file that have been read, then call setText() once to place everything in your View. Without appending, you are essentially overwriting the 'w' variable every time your while loop runs through, which is why you are receiving the last line from your text file.

how to use Input stream reader to load files from internal memory android

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();
}
}

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();
}

Android : Reading File

I am trying to get last 10 rows from file but not able to fetch.
i have two activities:
in the first, i want to write text from an EditText to a file.
in the second activity i try to read the stored data and write it to a textView
public class Date_Location extends Activity {
ImageView imageView;
EditText editTextDate, editTextLocation, editTextEdit;
private static final String TAG = Date_Location.class.getName();
private static final String FILENAME = "myFile.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.date_location);
editTextDate = (EditText) findViewById(R.id.editText1);
editTextLocation = (EditText) findViewById(R.id.editText2);
editTextEdit = (EditText) findViewById(R.id.editText3);
imageView = (ImageView) findViewById(R.id.next);
}
public void goNext(View view) {
String Date = editTextDate.getText().toString();
String Location = editTextLocation.getText().toString();
String Comment = editTextEdit.getText().toString();
writeToFile(Date);
writeToFile(Location);
writeToFile(Comment);
Intent intent = new Intent(this, Detail_Data.class);
startActivity(intent);
Date_Location.this.finish();
}
private void writeToFile(String data) {
String newline = "\r\n";
try {
OutputStreamWriter oswName = new OutputStreamWriter(openFileOutput(
FILENAME, Context.MODE_APPEND));
oswName.write(newline);
oswName.write(data);
oswName.close();
} catch (IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
}
}
}
And my second Activity is below
public class Detail_Data extends Activity {
TextView textView1;
ImageView imageView;
private static final String FILENAME = "myFile.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_data);
textView1 = (TextView) findViewById(R.id.textView1);
imageView = (ImageView) findViewById(R.id.imageView2);
String date = readFromFile();
textView1.setText(date);
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput(FILENAME);
ArrayList<String> bandWidth = new ArrayList<String>();
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+'\n');
bandWidth.add(receiveString);
if (bandWidth.size() == 10)
bandWidth.remove(0);
}
ret = stringBuilder.toString();
inputStream.close();
}
} catch (FileNotFoundException e) {
Log.i("File not found", e.toString());
} catch (IOException e) {
Log.i("Can not read file:", e.toString());
}
return ret;
}
public void goNext(View view) {
imageView.setColorFilter(0xFFFF3D60, PorterDuff.Mode.MULTIPLY);
Intent intent = new Intent(this, Agreement.class);
startActivity(intent);
Detail_Data.this.finish();
}
}
please if any one have any idea then help me. I have tried with other solution too but then also i am not getting last 10 records. Instead of last 10 data i am getting all the records which is written in file.
Firstly, If you are writing file on SDcard, be sure that you have added the uses-permission tag in AndroidManifest.xml
<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Secondly, don't forget flush()
oswName.write(data);
oswName.flush();
oswName.close();
Then, there is something wrong with your readFromFile() method,
remove this line from while loop
stringBuilder.append(receiveString+'\n');
and add this right after the while loop
for(String str : bandWidth)
stringBuilder.append(str + "\n");
readFromFile() should be like following
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput(FILENAME);
ArrayList<String> bandWidth = new ArrayList<String>();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
bandWidth.add(receiveString);
if (bandWidth.size() == 10)
bandWidth.remove(0);
}
for(String str : bandWidth)
stringBuilder.append(str + "\n");
ret = stringBuilder.toString();
inputStream.close();
}
} catch (FileNotFoundException e) {
Log.i("File not found", e.toString());
} catch (IOException e) {
Log.i("Can not read file:", e.toString());
}
return ret;
}
After opening the input/output stream, use that methods:
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Files {
public static String readStringFile(FileInputStream fis) throws java.io.IOException {
StringBuffer fileContent = new StringBuffer("");
byte[] buffer = new byte[1024];
while (fis.read(buffer) != -1) {
fileContent.append(new String(buffer));
}
return fileContent.toString();
}
public static void writeStringFile(FileOutputStream fos, String text) throws java.io.IOException {
fos.write(text.getBytes());
}
}
First, create the FileInputStream or FileOutputStream with your desired file name and then call the methods above. Please notice that the methods only work for reading and writing strings.
You store each line to list and remove 0 position only if list size = 10
So as 1st step store all file in list:
Instead
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
if (bandWidth.size() == 10)
bandWidth.remove(0);
}
Write
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
}
After copy last 10 lines to new list.
For example if you have :
List<String> bandWidth = new ArrayList<String>(Arrays.asList("a1", "a2", "a3","a4", "a5", "a6","a7", "a8", "a9","a10", "a11", "a12"));
Than with subList:
List<String> bandWidth10rows= bandWidth.subList(bandWidth.size()-10, bandWidth.size());
It will copy last 10 list items to new list.
Totally it should be something like:
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString+'\n');
bandWidth.add(receiveString);
}
List<String> bandWidthLastTenRows= bandWidth.subList(bandWidth.size()-10, bandWidth.size());

FileReader to read from bottom to top or stringbuffer?

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());

Categories

Resources