I am trying to write some json data to the file, below is what i have tried.
JSONObject obj = new JSONObject();
try {
obj.put("name", "mkyong.com");
} catch (JSONException e2) {
e2.printStackTrace();
}
try {
obj.put("age", new Integer(100));
} catch (JSONException e2) {
e2.printStackTrace();
}
ArrayList list = new ArrayList();
list.add("msg 1");
list.add("msg 2");
list.add("msg 3");
try {
obj.put("messages", list);
} catch (JSONException e1) {
e1.printStackTrace();
}
FileOutputStream fs;
String filename = "Sample.json";
try {
fs = openFileOutput(filename, Context.MODE_APPEND);
fs.write(obj.toString().getBytes());
fs.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I dont get any errors though, but the file created is not visible. Should i have to read it to verify its written properly?? It would be of great help if i can see the created file in the src folder since i write many stuff, its easy to validate.
Probably lame, but we can locate the file in the DDMS perspective and pull out tag will will be visible!! From there, we can pull it out and view it from the local computer!!
Try to change
String filename = "Sample.txt";
instead of
String filename = "Sample.json";
Related
I am trying to store the json data to the file.This is the code for creating directories and file.
public void filecreation() throws IOException {
File mediaStorageDir = new File(getActivity().getFilesDir() + "/" +
"Zerribelum");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("App", "failed to create directory");
// return null;
} else {
Log.d("Apppppp", "create directory");
File textfolder = new File(mediaStorageDir, "Text");
if (!textfolder.exists()) {
textfolder.mkdirs();
File newtext = new File(textfolder, "dummy.txt");
stream = new FileOutputStream(newtext);
bw = new BufferedWriter(new OutputStreamWriter(stream));
}
File imagefolder = new File(mediaStorageDir, "Image");
if (!imagefolder.exists()) {
imagefolder.mkdirs();
}
File videofolder = new File(mediaStorageDir, "Video");
if (!videofolder.exists()) {
videofolder.mkdirs();
}
}
}
}
I want put the json data to the file.
try {
JSONArray mJsonTopicArray = mJsonObject.getJSONArray(AppConstants.APIKeys.TOPICS_LIST);
for (int i = 0; i < mJsonTopicArray.length(); i++) {
Topics mTopics = new Topics();
mTopics.setId(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.ID));
mTopics.setTitle(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.TOPICS));
mTopics.setImage(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.TOPICS_IMAGE));
mTopics.setDescription(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.DESCRIPTION));
mTopicsArrayList.add(mTopics);
bw.write(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.DESCRIPTION));
bw.newLine();
}
bw.close();
mCategoryListRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mCategoryListRecyclerView.setHasFixedSize(true);
mCategoryListRecyclerView.setAdapter(new ParallaxRecyclerAdapter(context, HomeFragment.this, mTopicsArrayList));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
The probelm is if I have'nt add bw.write and bw.close() lines the data will display in recyclerview. But when I add this lines, data is adding to file but not showing in recylcer view. I want both to be done. What will be the problem?
Note: public FileOutputStream stream;
public BufferedWriter bw; Initialised.
Check your stacktrace, your code must be crashing and you arent noticing it because of try catch
Attach a debugger and check the items in the arraylist once the adapter is initialized. If items are present it will work
solved,the issue is because of Nullpointer Exception.So handled using try catch.
try {
bw.write(mJsonTopicArray.getJSONObject(i).getString(AppConstants.APIKeys.TOPICS));
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
I have an arraylist of objects in a fragmentActivity
private List<Movie> myMovies = null;
I have options to add, remove and all that from the movie list, but once I close the application all is lost. How can I save the array into a file and retrieve the array from the file?
I have:
public void writeArray() {
File f = new File(getFilesDir()+"MyMovieArray.srl");
try {
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream objectwrite = new ObjectOutputStream(fos);
objectwrite.writeObject(myMovies);
fos.close();
if (!f.exists()) {
f.mkdirs();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public ArrayList<Movie> read(Context context) {
ObjectInputStream input = null;
ArrayList<Movie> ReturnClass = null;
File f = new File(this.getFilesDir(),"MyMovieArray");
try {
input = new ObjectInputStream(new FileInputStream(f));
ReturnClass = (ArrayList<Movie>) input.readObject();
input.close();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return ReturnClass;
}
but it is not working. getFilesDir() always points to a nullpointerexception
Is this the right way to do it?
Any sugestions on how can I save the array into a file and retrieve the array from the file?
UPDATE 1: Found the fix, just needed to write File f = new File(getFilesDir(), "MyMovieArray.srl");
New problem arrised: I have this code for onCreate:
myMovies = read(this);
if(myMovies==null){
myMovies = new ArrayList<Movie>();
populateMovieListWithExamples();
writeArray();
}
Everytime I start the application it always shows the list with the populate examples... if I add or remove once I reopen it is always the same list. Sugestions?
UPDATE 2 Just needed Movie class to be serializable. Thank you all for your help. Have a good day everyone
You are saving to MyMovieArray.srl but reading from MyMovieArray. Read also from MyMovieArray.srl
File object should be created like this (both in write and read):
File f = new File(getFilesDir(), "MyMovieArray.srl");
Use File f = new File(getFilesDir(), "MyMovieArray.srl");
in both writeArray() and read() methods
Honestly, I've searched a lot do this task so I ended up trying various methods but nothing worked until I ended up on this code. It works for me perfectly like it should, so I do not want to change my code.
The help I need is to put this code in a such a way that it begins to read a file, but if it the file doesn't exist then it will create a new file.
Code for saving data:
String data = sharedData.getText().toString();
try {
fos = openFileOutput(FILENAME, MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Code for loading data:
FileInputStream fis = null;
String collected = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte [fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
So If I add the saving data code in to the "FileNotFoundException" catch of the loading data part then could I achieve what I want?
Add
File file = new File(FILENAME);
if(!file.exists())
{
file.createNewFile()
// write code for saving data to the file
}
above
fis = openFileInput(FILENAME);
This will check if there exists a File for the given FILENAME and if it doesn't it will create a new one.
If you're working on Android, why don't you use the API's solution for saving files?
Quoting:
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
You should really read the whole document, they explain pretty well the basic ways of creating or accessing files, you can also check the different ways of storing data.
But regarding your original question:
So If I add the saving data code in to the "FileNotFoundException"
catch of the loading data part then could I achieve what I want?
Yes, you could achieve it.
Try this one:
public static void readData() throws IOException
{
File file = new File(path, filename);
if (!file.isFile() && !file.createNewFile()){
throw new IOException("Error creating new file: " + file.getAbsolutePath());
}
BufferedReader r = new BufferedReader(new FileReader(file));
try {
// ...
// read data
// ...
}finally{
r.close();
}
}
Ref: Java read a file, if it doesn't exist create it
What I am trying to do is store a JSON file as a string in internal storage to access it later. The reasoning behind this is to not have to access the server on every request, as this data is constant. Once it is stored once, it doesn't have to be retrieved again unless there is some sort of update. File storage isn't something I've done before, and I was hoping someone could give me a hand. My current code is throwing a null pointer exception at this line:
File file = new File(getFilesDir(), fileName);
My code:
protected String doInBackground(String[] runeId) {
String url = "https://prod.api.pvp.net/api/lol/static-data/" + region + "/v1.2/rune/" + runeId[0] + "?api_key=" + api_key;
JSONParser jsonParser = new JSONParser();
JSONObject runeInfo = jsonParser.getJSONFromUrl(url);
String jsonString = runeInfo.toString();
String fileName = "runeInfo";
File file = new File(getFilesDir(), fileName);
String readJson = null;
if(!runesCached) {
Log.d("Cache", "Caching File");
try {
FileOutputStream os = new FileOutputStream(file);
os.write(jsonString.getBytes());
os.close();
Log.d("Cache", "Cache Complete");
runesCached = true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String name = null;
try {
FileInputStream fis;
File storedRuneInfo = new File(getFilesDir(), fileName);
fis = new FileInputStream(storedRuneInfo);
fis.read(readJson.getBytes());
JSONObject storedJson = new JSONObject(readJson);
try {
name = storedJson.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
}
Try this, instead:
File file = new File(getFilesDir().toString(), fileName);
getFilesDir() returns a File, not a String, which the File class constructor takes as a parameter.
getFilesDir()toString() should return something like /data/data/com.your.app/
EDIT:
This gives the same error. How about:
try {
FileWriter fstream;
BufferedWriter out;
fstream = new FileWriter(getFilesDir() + "/" + "filename");
out = new BufferedWriter(fstream);
out.write(jsonString.getBytes());
out.close();
} catch (Exception e){}
Hello Im trying to save the language save by the user in my game
I have made a test to see if the script create the file and read it good.
Im using ini4j to store the value of language in a ini file.
I have no file, on the 1st start, programm create the empty file in the Local directory and fill it with value (language=fr) for test.
On 2nd start, the programm check if the file exist, then open it to read the value
The problem is that the 'lang' variable seems to be empty when it read it by my function sic_Language.setLanguage(String text);
My code
String lang;
Wini ini;
//Read
if (Gdx.files.local("mygame.ini").exists()) {
//Open file
try {
ini = new Wini(Gdx.files.local("mygame.ini").file());
} catch (InvalidFileFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Read values
lang = ini.get("interface", "language");
sic_Language.setLanguage(lang); //Set language
}
//Write
else {
//Create file
try {
Gdx.files.local("mygame.ini").file().createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//Open file
try {
ini = new Wini(Gdx.files.local("mygame.ini").file());
} catch (InvalidFileFormatException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
//Write values
ini.put("interface", "language", "fr");
try {
ini.store();
} catch (IOException e) {
e.printStackTrace();
}
sic_Language.setLanguage("fr"); //Set language
}