Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get file read line by line

I have a file containing text in separate line.
I want to display line first, and then if I press a button, the second line should be displayed in the TextView and the first line should disappear. Then, if I press it again, the third line should be displayed and so on.

Should I have to use TextSwitcher or anything else? How can I do that?

like image 598
Sunny Avatar asked Aug 24 '11 12:08

Sunny


People also ask

Which method is used to read file line by line?

We can use java. io. BufferedReader readLine() method to read file line by line to String. This method returns null when end of file is reached.

How do I read a text file line by line in Python?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.

When reading a file line by line the exact contents can be printed by?

Reading a File Line-by-Line in Python with readline() This code snippet opens a file object whose reference is stored in fp , then reads in a line one at a time by calling readline() on that file object iteratively in a while loop. It then simply prints the line to the console.


1 Answers

You tagged it as "android-assets" so I'm going to assume your file is in the assets folder. Here:

InputStream in;
BufferedReader reader;
String line;
TextView text;

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    text = (TextView) findViewById(R.id.textView1);
    in = this.getAssets().open(<your file>);
    reader = new BufferedReader(new InputStreamReader(in));
    line = reader.readLine();

    text.setText(line);
    Button next = (Button) findViewById(R.id.button1);
    next.setOnClickListener(this);
}

public void onClick(View v){
    line = reader.readLine();
    if (line != null){
        text.setText(line);
    } else {
        //you may want to close the file now since there's nothing more to be done here.
    }
}

Give this a try. I haven't been able to verify that it works completely, but I believe this is the general idea you want to follow. Naturally you'll want to replace any R.id.textView1/button1 with the names that you've specified in your layout file.

Also: There is very little error checking here for the sake of space. You will want to check that your asset exists and I'm pretty sure there should be an try/catch block when you open the file for reading.

Edit: Big error, It's not R.layout, it's R.id I have edited my answer to fix the problem.

like image 144
Otra Avatar answered Oct 07 '22 00:10

Otra