Search code examples
javaandroidstorageinternalinternal-storage

FileOutputStream not working in Android


I'm using internal storage for the first time and my openFileOutput is giving me an error. I am not sure how to make this work, but the method below works perfectly fine if the FileOutputStream is removed. Thank you!

public void Addition(View view) {

    int num1 = numberone.getText().toString().trim().length();
    int num2 = numbertwo.getText().toString().trim().length();
    String numone = numberone.getText().toString();
    String numtwo = numbertwo.getText().toString();

    if(num1 == 0 || num2 == 0){
    TextView value = (TextView)findViewById(R.id.answer);
    value.setText("Numbers not entered");
    }
    else if(numone.equals("+") || numtwo.equals("+") || numtwo.equals("-") || numone.equals("-")){
        TextView value = (TextView)findViewById(R.id.answer);
        value.setText("Please enter numbers");
    }
    else{

answer = Float.parseFloat(numberone.getText().toString()) + Float.parseFloat(numbertwo.getText().toString());;

TextView value = (TextView)findViewById(R.id.answer);
value.setText("Your sum is " + answer);
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);

    }

}

Solution

  • If your class doesn't extends a Context subclass, you need to pass a Context instance (an Activity, a Service, etc) to call openFileInput. Also you need to catch java.io.FileNotFoundException or add throws declaration to your method.

    Hope it helps.