0
I’m trying to reuse a class, which writes the file to the internal storage.
In the first line of try
, the result is null
(from activity
) and makes a mistake.
When I execute this code on 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;
}
}
Static context is a bad idea. Why don’t you pass this context in the constructor?
– Pablo Almeida
Or directly in the method.
– ramaral
Okay, thanks for the help. .
– Magno Malkut