How can I get the Application Data Dir in Android Fragment or standard Java class (that is not an Activity).
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
private void readFile() {
try{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
books = (List<Book>)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());
}
}
Problem is that this class contructor requires a String DataDir to be passed like so
public class BookSvcSioImpl implements IBookSvc {
private final String TAG = "BookSvcSioImpl";
private List<Book> books = null;
private String dataDir = null;
private String filePath = dataDir + "/myBooks.sio";
public BookSvcSioImpl(String appDataDirectory){
this.dataDir = appDataDirectory;
readFile();
}
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
String dataDir = getApplicationInfo().dataDir;
BookSvcSioImpl sioService = new BookSvcSioImpl(dataDir);
sioService.create(enteredBook);
I am not able to do this in a Fragment or Java class.
I am not able to do this in a Fragment
Call getActivity()
on the Fragment
to obtain the Activity
that hosts the fragment.
Note that getFilesDir()
on the Activity
(or other Context
) is a better choice than getApplicationInfo().dataDir
, as I do not know if dataDir
adjusts to handle multiple accounts on tablets.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.