Question

I have a piece of code that is not working as I want.

deleteFile(mealFile);
    //TODO: Error
    try{
        FileOutputStream fos = openFileOutput(mealFile, MODE_APPEND);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        for(int i=0; i<temp_name.size(); i++){
            if(!(temp_name.get(i).equals(mealName.getText().toString()))){
                osw.append(temp_name.get(i) + "\t");
                osw.append(temp_meals.get(i) + "\t");
                osw.append(temp_scale.get(i) + "\t");
                System.getProperty("line.separator");
            }
        }
    }catch(Exception e){
        updateWarningMessage(6);
    }

There must be something obvious Im missing out. This code does not want to append anything to the file. I know the code is not failing (no exception es), I know the ArrayLists Im trying to append are not empty and contain Strings (I have even tried with just "osw.append("test");" with no luck). I know the for-loop is running as many times as it is supposed to, and as I somewhat said, I know the "if" is working. At first, I though it was a delay in the file deletion or something, but I tried adding a method that writes text to this file directly after the DeleteFile(), and this part worked.. And still, this code does not append anything.

Does anyone have any clue what can be wrong?? Im totally lost, the other method Im using to append looks somewhat the same. Im gonna try now to pass the ArrayLists to a new method and try add it from there, but I do not like leaving such odd behaivour unsolved. I hope Im just missing out on something obvious from coding all day. Can anyone spot anything?

Was it helpful?

Solution

I would flush() after every iteration and close() the stream when finished, as that's the usual procedure when working with files.

try{
        FileOutputStream fos = openFileOutput(mealFile, MODE_APPEND);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        for(int i=0; i<temp_name.size(); i++){
            if(!(temp_name.get(i).equals(mealName.getText().toString()))){
                osw.append(temp_name.get(i) + "\t");
                osw.append(temp_meals.get(i) + "\t");
                osw.append(temp_scale.get(i) + "\t");
                System.getProperty("line.separator");
                osw.flush();
            }
        }
        osw.close();
    }catch(Exception e){
        updateWarningMessage(6);
    }

OTHER TIPS

It could be that in your manifest you forgot to add the writing to external storage

Solution:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top