my app crashes because of the following;
loadJsonFromAsset() method reads the JSON file after writing it with the update() method, but instead it goes straight to the reading part and my app crashes because the file video.json doesn't exist, JSON doesn't get written, it has to do with how slow the Volley request is? Or is how I create the file? I write and read the JSON file to cache it on the user's phone and if the file already exists on the phone it goes straight to the reading part(but I haven't implemented it if file exits). For example, it works if I remove the reading part of my code loadJSONFromAsset() and instead run the update() method the JSON file gets created with the JSON data I requested and then if I re-run the program with the loadJSOnFromAsset() and bam I read the data and my app doesn't crash.I think my problem is that I'm storing the cache to slowly?
loadJsonFromAsstet() reads JSON
public String loadJSONFromAsset() {
update();
String json = null;
try {
FileInputStream is = getActivity().openFileInput("video.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
Toast.makeText(getActivity(), "Error Fetching Data", Toast.LENGTH_LONG).show();
return null;
}
return json;
}
update(); Writes JSON with the requested data
public void update(){
// Formulate the request and handle the response.
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, (String )null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_LONG).show();
try {
FileOutputStream fos = getActivity().openFileOutput("video.json", Context.MODE_PRIVATE);
Writer out = new OutputStreamWriter(fos);
out.write(response.toString());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error Fetching Data", Toast.LENGTH_LONG).show();
}
});
//remove cash
jsonObjectRequest.setShouldCache(false);
mRequestQueue.add(jsonObjectRequest);
}
Thanks!! :)