Cam Connor
Cam Connor

Reputation: 1231

I'm trying to read in a file on android

I am making an app where the text of a button is a random string, and all of the random strings are stored in a .txt file. I made a method that return a string and for some reason whenever I run the app the button is blank and there is no text on it. I know it is sommething to do with the file io because if I get the method to return a set String like "hi" then the text on the button will be hi. I am adding my oncreate method just in case.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    String str = "Hello there!";
    TextView text = (TextView) findViewById(R.id.question);
    text.setText(execute());

}

above is my oncreate below is my fileio file

public static String execute() {
 String number[] = new String[100];
 double x = Math.random()*47;
 int random = (int) Math.round(x);

    int act = 0;

    //The try/catch statement encloses some code and is used to handle errors and exceptions that might occur
    try { 

        // Read in a file
        BufferedReader in = new BufferedReader(new FileReader("activities")); 

        String str; 
        while ((str = in.readLine()) != null) { 
            number[act] = str;
            act++;
        } 
        in.close();
        } catch (IOException e) { 
            System.out.println("Can not open or write to the file.");
        } 



    return number[random];
}

Upvotes: 0

Views: 76

Answers (1)

Rahul
Rahul

Reputation: 45060

You have mentioned that you try to read from a .txt file, but in the FileReader, you've given just a name called activities without any file extension. That's why nothing is getting displayed.

new FileReader("activities.txt"); // Should be something like this

Also, it either needs to be a relative URL or even better, try to put your file in the assets folder and then try to read it from there. That's a better and cleaner approach.

Check out this answer on how to read a file from assets folder.

Upvotes: 2

Related Questions