我正在开发一个将 json 文件保存到设备缓存中的小项目。 在我的 Home_fragmen 上,我从网络文件中加载 json 并保存文件。
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("photos");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String id = hit.getString("id");
mlist.add(new items(id));
}
mAdapter = new main_adapter(getActivity(), mlist);
mRecyclerView.setAdapter(mAdapter);
// Cashing json file
jsonFile= response.toString();
cacheJson(jsonFile);
}
private void cacheJson(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(getActivity().openFileOutput("jsontxt.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
这是我用来从缓存中读取数据的代码
private String readJson() {
String jsonArray = "";
try {
InputStream inputStream = getActivity().openFileInput("jsontxt.txt");
if ( inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receivingString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receivingString = bufferedReader.readLine()) != null) {
stringBuilder.append(receivingString);
}
inputStream.close();
jsonArray = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "Can not read file: " + e.toString());
}
return jsonArray;
}
所有这些工作都在我的主要 fragment 上进行,因为那里拥有一切......现在我要做的是从一个新 fragment 的不同 fragment 读取缓存。
我试过这些但没有用。
Home_fragment jsonFile = new Home_fragment ();
String s = jsonFile.cachejson();
Log.e(TAG, "JSON FILE: " + s);
我的问题是如何从辅助 fragment 读取访问我主 fragment 上的 readJson()。
最佳答案
第 1 步: 在 fragment 1 中,将您的 json 结果放入 Bundle
Bundle bundle = new Bundle();
bundle.putString("key","abc"); // Put anything what you want
Fragment_2 fragment2 = new Fragment_2();
fragment2.setArguments(bundle);
getFragmentManager()
.beginTransaction()
.replace(R.id.content, fragment2)
.commit();
第 2 步: 在 fragment 2 中
Bundle bundle = this.getArguments();
if(bundle != null){
// handle your code here.
}
第 3 步 创建一个方法 readjson 作为读取包参数的全局访问
public static String readJson(String jsonStr) {
try {
// put your code
}
} catch (FileNotFoundException e) {
Log.e(TAG, "File not found: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "Can not read file: " + e.toString());
}
return jsonArray;
}
希望对你有帮助
关于java - 如何从 fragment 中调用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53918314/