android - java.io.FileNotFoundException when writing to internal memory -
i've written functions making/editing files , worked fine. however, needed use these function in many activities, i've found guide on how globalize functions, , somehow did it. after put functions in separate class, stopped working. logcat not working, can't trycatch it, if could, don't think me.
here part of mainactivity.java:
myhelper myhelp = new myhelper(this); @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); myhelp.synchronizedb("filename"); }
here part of myhelper.java:
public class myhelper extends actionbaractivity { context mcontext; public myhelper(context context){ this.mcontext = context; } public void writefile(string fname, string fcontent) { bufferedwriter bw = new bufferedwriter(new outputstreamwriter(openfileoutput(fname, mode_append))); bw.write(fcontent); bw.close(); } public void synchronizedb(string filename) { writefile(filename, "blabla"); } }
you improperly making class not utilized activity subclass extend actionbaractivity. not workable call new
subclass of activity, activity has been created system functional, , after oncreate() method has been called system.
likely hit upon making helper class sort of fake activity, in order able use methods inherited activity (and similar) such openfileoutput(). not workable.
a more workable solution drop "extends actionbaractivity" class name, , either utilize passed in context reference:
mcontext.openfileoutput(...)
or, perhaps better, discovered internal storage location in constructor , save later use:
public class myhelper { context mcontext; file mdir; public myhelper(context context){ this.mcontext = context; this.mdir = context.getfilesdir(); } public void writefile(string fname, string fcontent) { bufferedwriter bw = new bufferedwriter(new outputstreamwriter( new fileoutputstream(new file(mdir, fname), mode_append))); bw.write(fcontent); bw.close(); }
further, because of rule activity class being functional after it's oncreate() called, must move creation of helper class or after utilizing activity's oncreate()
myhelper myhelp; //can't initialize our context not yet valid @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); myhelp = new myhelper(this); //now have working context pass myhelp.synchronizedb("filename"); }
Comments
Post a Comment