title: How to Get Application Data Dir in Android
body: <p>How can I get the Application Data Dir in Android Fragment or standard Java class (that is not an Activity).</p>
  
  <p>I am doing an assignment that requires using Serialization to perform CRUD operation in Android. So far I have a standard Java Class that performs read and write like so</p>
  
  <pre><code>private void readFile() {
      try{
          ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
          books = (List&lt;Book&gt;)ois.readObject();
          ois.close();
      }catch (Exception e){
          Log.e(TAG, e.getMessage());
      }
  }
  
  private void writeFile(){
      try {
          ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
          oos.writeObject(books);
          oos.flush();
          oos.close();
      } catch (Exception e){
          Log.e(TAG, e.getMessage());
      }
  }
  </code></pre>
  
  <p>Problem is that this class contructor requires a String DataDir to be passed like so </p>
  
  <p>public class BookSvcSioImpl implements IBookSvc {</p>
  
  <pre><code>private final String TAG = "BookSvcSioImpl";
  private List&lt;Book&gt; books = null;
  private String dataDir = null;
  private String filePath = dataDir + "/myBooks.sio";    
  
  
  public BookSvcSioImpl(String appDataDirectory){
      this.dataDir = appDataDirectory;
      readFile();
  }
  </code></pre>
  
  <p>I use this String parameter to construct the file path. My question how can I get the Application Data Directory in a Fragment or in standard Java class that is not an Activity. In an Activity I can get it by calling getApplicationInfo.DataDir like so </p>
  
  <pre><code>  String dataDir = getApplicationInfo().dataDir;
                  BookSvcSioImpl sioService = new BookSvcSioImpl(dataDir);
                  sioService.create(enteredBook);
  </code></pre>
  
  <p>I am not able to do this in a Fragment or Java class.</p>