-3

I want to find the average of a series of values that the user chooses, with the help of a RatingBar. Each time the user presses a Button, I want to write the value of the RatingBar to a file. But when I try to save the value, the new value overrides the old one in the file instead of appending the value. I would prefer to save the file in the internal storage.

Afterwards, I want to fetch all the values and put them into a ArrayList. And calculate the average of all the values given.

I started in C#, so it would be easy with WriteLine() and ReadLine() but writeline does not exist (at least, I didn't find in my research) and in some situations, readline is deprecated.

I tried to do this:

 private void writeMyArray(double rate){
    try{
        FileWriter fileWritter = new FileWriter("test3",true);
        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
        bufferWritter.write(Double.toString(rate));
        bufferWritter.close();

    }catch(IOException e){
        e.printStackTrace();
    }

private void readMyArray(ArrayList<String> list){
    try {
        InputStream inputStream = openFileInput("test3.txt");
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader reader = new BufferedReader(inputStreamReader);
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                list.add("");
                break;
            }
            list.add(line);
        }
        reader.close();

} catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}

When I press the button, with this code:

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            rating = ratingbar.getRating();
            writeToFile(Double.toString(rating));
            writeMyArray(ratingbar.getRating());

            button.setText(getText(R.string.obrigado) + "!" + readFromFile() + arraydays.get(0));// + media(Double.parseDouble(readMyArray()), Integer.parseInt(stackread())));
            //button.setText(getText(R.string.obrigado)+"!");
            //ratingbar.setEnabled(false);
           // button.setEnabled(false);
        }
    });

I get this logcat error:

07-06 10:54:44.180  29840-29840/com.example.emilio.notification E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.emilio.notification, PID: 29840
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
        at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
        at java.util.ArrayList.get(ArrayList.java:308)
        at com.example.emilio.notification.MainActivity$2.onClick(MainActivity.java:116)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5257)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

the write/read file method is for other purpose but working, so the problem is in my array code.

The other file code

private void writeToFile(String data) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("estrela.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();

    } catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }
}


private String readFromFile() {

    String ret = "";

    try {
        InputStream inputStream = openFileInput("estrela.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);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    } catch (FileNotFoundException e) {
        Log.e("login activity", "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e("login activity", "Can not read file: " + e.toString());
    }

    return ret;
}
Mrtn
  • 107
  • 5
António Paulo
  • 351
  • 3
  • 18
  • Java and android is in the tags so i supposed that everybody could associate the tags with the language that I want to be helped (not talking about the title). My code isn't needed for what I want since is a generic context. – António Paulo Jul 06 '15 at 10:51
  • possible duplicate of [How To Read/Write String From A File In Android](http://stackoverflow.com/questions/14376807/how-to-read-write-string-from-a-file-in-android) – B. Kemmer Jul 06 '15 at 10:55
  • No, because I need the arraylist. I added the current code. – António Paulo Jul 06 '15 at 10:58
  • So you have to change 1 Line. Instead of `stringBuilder.append(receiveString);` you have to write `list.add("");`. – B. Kemmer Jul 06 '15 at 11:00
  • Your Logcat output already tells you, what is wrong. `arraydays.get(0)` arraydays has a size of 0, but you are trying to get the first value out of it. You are appending to a variable called **list** with `list.add(line)`. That's all i understand. your code is unreadable though. – B. Kemmer Jul 06 '15 at 11:15

2 Answers2

2

I assume you are looking for three methods here. One that appends a double to a file, another reads the numbers to an ArrayList<Double>, and the third calculates the average rating.

Write:

public void writeToFile(double rate) throws IOException {
    FileOutputStream fout;
    fout = new FileOutPutStream("myfile.txt", true);
    new PrintStream(fout).println(rate);
    fout.close();
}

Read:

public List<Double> readFromFile() throws IOException {
    List<Double> rateList = new ArrayList<Double>();
    Scanner s = new Scanner(new FileInputStream("myfile.txt"), "utf-8");
    while (s.hasNextLine()) {
        rateList.add(Double.parseDouble(s.nextLine()));
    }
    return rateList;
}

Find average rating:

public double findAverageRating(List<Double> rateList) {
    double averageRating = 0;
    for (double r : rateList)
        averageRating += r;
    return averageRating / rateList.size();
}

This means you can do the following in your button listener:

writeToFile(ratingbar.getRating());
button.setText(findAverageRating(readFromFile()));
Reitan
  • 21
  • 5
0

Your Logcat output already tells you, what is wrong. You call arraydays.get(0), while arraydays seems to has a size of 0, but you are trying to get the first value out of it. You are appending to a variable called list with list.add(line). That's all I understand. Your code is unreadable though.

B. Kemmer
  • 1,517
  • 1
  • 14
  • 32