I'm trying to create a file in a JSONhelper class, that is not an activity.
From what I've read, I can't use the method openFileOutput(String name, Context.MODE_PRIVATE).
I guess that only works when you're creating a file from an activity. But I can't seem to find out how to create a file from a helper class. Here is my class and what I'm trying to accomplish is pretty straight forward.
Please help and thanks in advance.
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import com.checkinsystems.ez_score.model.Match;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import static android.content.Context.MODE_PRIVATE;
import static java.security.AccessController.getContext;
public class JSONhelper {
private static final String FILE_NAME = "new_match.json";
private static final String TAG = "JSONHelper";
public static boolean exportToJSON(Context context, List<Match> matches) {
Matches newMatch = new Matches();
newMatch.setMatches(matches);
Gson gson = new Gson();
String jsonString = gson.toJson(newMatch);
Log.i(TAG, "exportToJSON: " + jsonString);
FileOutputStream fileOutputStream = null;
File file = new File(FILE_NAME);
try {
fileOutputStream = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
fileOutputStream.write(jsonString.getBytes());
return true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
public static List<Match> importFromJSON(Context context) {
FileReader reader = null;
try {
File file = new File(FILE_NAME);
reader = new FileReader(file);
Gson gson = new Gson();
Matches matches = gson.fromJson(reader, Matches.class);
return matches.getMatches();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
static class Matches {
List<Match> matches;
public List<Match> getMatches() {
return matches;
}
public void setMatches(List<Match> matches) {
this.matches = matches;
}
}
}