Issue
I have an app that has a SplashScreen
and a MainActivity
. In the MainActivity
a FrameLayout
gets replaced by fragments. But this is just a basic understanding and I don't think it's really needed for my problem.
In my SplashScreen I'm checking if a file exists on the internal storage. If it does it gets read out. If it doesn't, it gets downloaded from the internet. So far so good. Now, when the user is in the MainActivity he has different options. Dependent on that option a Fragment will be opened and displays data. This data is different. So now I wanted to do the same like in the SplashScreen there. Check if the file exists. If it does, read it out, otherwise download from Internet. The problem I'm encountering is, that it seems that reading and writing is not possible via Fragments. Is that correct?
The fragment stars an AsyncTask and should do the downloading in there.
This is the code I have in the Fragment for writing to a file
private void writeToFile(String data, String filename) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput( filename, MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
But the problem I have is at MODE_PRIVATE
- The error I have is MODE_PRIVATE cannot be resolved to a variable
. How can I set the mode to private in the fragment?
Then, when I want to read a file it works in the SplashScreen like that
inputStream = openFileInput ( filepath )
But in the fragment I get the error
The method openFileInput(String) is undefined for the type WeekFragment.MainAsyncTask
How exactly do I write and read from files within a fragment?
Solution
MODE_PRIVATE is constant of Context class. So you can access it from anywhere using Context.MODE_PRIVATE
.
So in your code use like
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(getActivity().openFileOutput( filename, Context.MODE_PRIVATE));
Answered By - Pankaj Kumar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.