java - openFileOutput not working properly inside a singleton class - ideas/workarounds? -


as novice android developer, i've faced bit strange problem. want create class, methods other classes-activities-whatever use working files in special way. let`s simplicity logging stuff. if following within activity (in onclick listener example), works fine:

fileoutputstream fout = openfileoutput("somefile", mode_private); outputstreamwriter osw = new outputstreamwriter(fout); osw.write("very important foobar"); osw.flush(); osw.close(); 

but when try enclose class , create singleton that:

public class logger extends baseactivity { //baseactivity "init" class extends activity  public static final logger instance = new logger(); private logger() {  // singleton }  public boolean dolog (string whattolog) {  try {      fileoutputstream fout = openfileoutput("somefile", mode_private);  outputstreamwriter osw = new outputstreamwriter(fout);  osw.write(whattolog);  osw.flush();  osw.close(); }      catch (ioexception ioe) { ioe.printstacktrace(); }        return true; } 

and call other activity that

logger.instance.dolog("foobar");   

app chrashes nullpointerexception (at line openfileoutput). suppose it`s because of improper use of singleton/activity here , rewriting code run service. maybe there better ideas solve issue? or workarounds?

thanks contributions in advance!

you based singleton on activity didn't start activity. therefore, doesn't have valid context, necessary io calls. see blundell's answer better singleton, 1 change: per android.app.application javadoc, singleton should application context given context via context.getapplicationcontext(). see why androidtestcase.getcontext().getapplicationcontext() return null example.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -