我的应用因以下原因崩溃;排球请求太慢
loadJsonFromAsset()方法和update()方法写入之后读取JSON文件,而是它直接到阅读部分,我的应用程序崩溃,因为该文件video.json不存在, JSON没有被写入,它与Volley请求的缓慢有关吗?或者是我如何创建文件?我编写并读取JSON文件以将其缓存在用户的手机上,并且如果手机中存在该文件,它将直接进入阅读部分(但如果文件退出,我还没有实现它)。例如,如果我删除我的代码的读取部分loadJSONFromAsset(),而是运行update()方法,JSON文件将使用我请求的JSON数据创建,然后如果我使用loadJSOnFromAsset()重新运行程序,和巴姆我读的数据和我的应用程序不会崩溃。我认为我的问题是我缓存缓存?
loadJsonFromAsstet()读取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;
}
更新();用请求的数据写入JSON
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);
}
谢谢!! :)
是的,这里确实存在这个问题,但我怎么能确定它已成功加载并保存? – MadBoy
确保您正确书写和阅读:[示例](http://stackoverflow.com/questions/14376807/how-to-read-write-string-from-a-file-in-android)。并且您只能在'onResponse'中阅读 –
如何在请求后使用数据更新recyclerviewview? – MadBoy