android - Why I am getting null pointer exception in the following code? -


this code, getting npe in function writefile(). point passing string writefile() method creates file using createfile() , writing string newly created file.

the file created in in directory, nothing being written it. string shows output @ logcat too, clear not empty string.

public file createfile( ){     file storagelocation = new file( environment.getexternalstoragedirectory(), path);     storagelocation.mkdirs();     if(!environment.getexternalstoragestate().equals(environment.media_mounted)) {         toast.maketext(context, "cannot use storage.", toast.length_short).show();     }     try{          file file = new file(storagelocation, getfilename()+".xml");          file.createnewfile();     }     catch( ioexception e){         e.printstacktrace();     }      return file; }  public string getfilename( ){     simpledateformat sdf = new simpledateformat("dd-mm-yyy",locale.uk);     return sdf.format(c.gettime( )); }   public void writefile( string text ){      try{ line 56>>   fileoutputstream fos = new fileoutputstream( createfile( ).getabsolutefile());             out = new dataoutputstream(fos);             out.writeutf(text);             toast.maketext(context.getapplicationcontext(), "backup successfull.", toast.length_long).show();             out.close();      }      catch( ioexception e){          e.printstacktrace();       toast.maketext(context.getapplicationcontext(), "backup failed.", toast.length_long).show();       }      catch( nullpointerexception e){          e.printstacktrace();           toast.maketext(context.getapplicationcontext(), "backup failed.", toast.length_long).show();           }  } 

edit : permissions set

<uses-permission android:name="android.permission.read_external_storage" /> <uses-permission android:name="android.permission.write_external_storage" /> 

here log logcat :

05-04 09:21:47.276: w/system.err(1137): java.lang.nullpointerexception 05-04 09:21:47.286: w/system.err(1137):     @ com.codepalette.ceeq.filemanager.writefile(filemanager.java:56) 05-04 09:21:47.286: w/system.err(1137):     @  com.codepalette.ceeq.backupmanager.backcalllogs(backupmanager.java:50) 05-04 09:21:47.286: w/system.err(1137):     @ com.codepalette.ceeq.backupmanager.takebackup(backupmanager.java:25) 05-04 09:21:47.296: w/system.err(1137):     @ com.codepalette.ceeq.home$2.onclick(home.java:154) 

there errors in code , doubt can run it. variable file (file) cannot returned declared, it's out of scope.

try change this:

try {      file file = new file(storagelocation, getfilename()+".xml");      file.createnewfile();      return file; } catch( ioexception e){     e.printstacktrace(); } return null; 

Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -