FileOutputStream failed context

0

I'm trying to reuse a class, which writes the file to internal storage. In the first line of try , the result is null (coming from activity ) and generates an error. When I run this code in mainActivity , it works.

public class Modelo {
    private static Context context;

    public void saveDisciplina(String nome, Float p1, Float p2){
        FileOutputStream fileOutputStream;
        String filename=" - "+nome;

        try {
            fileOutputStream=getContext().getApplicationContext()
                    .openFileOutput(filename,getContext().MODE_PRIVATE);
            fileOutputStream.write(("Nome da disciplina: "+filename+"\n").getBytes());
            fileOutputStream.write(("Nota P1: "+p1+"\n").getBytes());
            fileOutputStream.write(("Nota P2: "+p2+"\n").getBytes());
            fileOutputStream.close();
        }catch (IOException ex){

        }
        SharedPreferences pref = this.getSharedPreferences("com.fatec.karina.mygrades", 
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("nomed", String.valueOf(nomed));
        editor.putFloat("p1", p1);
        editor.putFloat("p2", p2);
        editor.commit();

    }

    public static Context getContext (){
        return context;
    }
}
    
asked by anonymous 14.11.2016 / 00:15

2 answers

0

You did it like this:

// ...
try {
    // ...
    fileOutputStream.close();
} catch (IOException ex){ //... }

In order to work, you need to do something like this:

// ...
PrintWriter writer = null;
try {
    FileOutputStream fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
    writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(fos)));
    writer.println(("Nome da disciplina: "+filename+"\n").getBytes());
    // ...
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (null != writer) {
        writer.close();
    }
}
// ...

Note: This is an example as basic as possible, you can shape from it to your needs, here with me it worked!

I hope it helps!

    
14.11.2016 / 16:00
0
public void saveDisciplina(String nome, Float p1, Float p2, Context context){
     // context recebendo no parametro do método ou no construtor
     // método
}
    
14.11.2016 / 14:59