Saturday, 15 August 2015

filewriter - Android: Write file from other class nullpointerexception -


I am trying to write a file from another category, but I get a null portefecope that I can not solve . The following code can be used primarily without any problem, but when I try to use it in my second class, I get an error.

  Public Zero WriteFile () {string text = "Hello world"; String filename = "TestFile.txt"; FileOutputStream fileApricotStream; Main activity maObj = new main activity (); Try {FileOutputStream = maObj.openFileOutput (fileName, maobj.MODE_PRIVATE); FileOutputStream.write (text.getBytes ()); FileOutputStream.close (); } Hold (IOException e) {e.printStackTrace (); }}  

You passed the activity reference instead of creating a new activity instance in the method of writing Do

  write public zip file (reference reference) {  

and remove

mainActivity maObj = new MainActivity (); As can be done in an Android application like this can not be instantified, change

  fileOutputStream = maObj.openFileOutput (filename, maobj.MODE_PRIVATE);  

to

  fileOutputStream = context.openFileOutput (filename, theme. MODE_PRIVATE);  

Once completed, your method should look like this:

  write public zero file (reference reference) {string text = "Hello world"; String filename = "TestFile.txt"; FileOutputStream fileApricotStream; Try {FileOutputStream = context.openFileOutput (filename, reference. MODE_PRIVATE); FileOutputStream.write (text.getBytes ()); FileOutputStream.close (); } Hold (IOException e) {e.printStackTrace (); }}  

Now call your method as

  file (main activity) as this;  

to main activity class.


No comments:

Post a Comment