简体   繁体   中英

How call a class from a fragment

I'm working on a small project that saves a json file into the device cache. On my Home_fragmen I'm loading the json from file from the web and also saving the file.

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();
        }
    }

This is the code that i'm using to read the data from the cache

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;
    }

All this work on my main fragment, because is where all have everything....now what I'm trying to do is to read the cache from a different fragment a new fragment.

I have tried doing these but is not working.

Home_fragment jsonFile = new Home_fragment ();
        String s = jsonFile.cachejson();
        Log.e(TAG, "JSON FILE: " + s);

My question is how can I read access the readJson() that is on my home fragment from a secondary fragment.

Make the method independent of the context (getActivity) of the fragment and pass that context as a parameter. And then place that method on a common accessible object from both fragments then you can access it from anywhere.

Step 1: In fragment 1, put your json result to 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();

Step 2: In Fragment 2

Bundle bundle = this.getArguments();

if(bundle != null){
     // handle your code here.
}

Step 3 create a method readjson as global access to read bundle arguments

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;
    }

i hope this help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM