Как назвать класс из фрагмента - PullRequest
0 голосов
/ 25 декабря 2018

Я работаю над небольшим проектом, который сохраняет файл 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;
    }

Вся эта работа над моим основным фрагментом, потому что там у всех есть все .... теперь я пытаюсь прочитать кэш из другого фрагмента нового фрагмента.

Iпытался сделать это, но не работает.

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

Мой вопрос: как я могу получить доступ для чтения readJson (), который находится на моем домашнем фрагменте из вторичного фрагмента.

Ответы [ 2 ]

0 голосов
/ 25 декабря 2018

Шаг 1: Во фрагменте 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: Во фрагменте 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;
    }

Надеюсь, эта помощь

0 голосов
/ 25 декабря 2018

Сделать метод независимым от контекста (getActivity) фрагмента и передать этот контекст в качестве параметра.А затем поместите этот метод на общий доступный объект из обоих фрагментов, и вы сможете получить к нему доступ из любого места.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...