即使使用“ OnAttach”方法,接口变量也将返回null

时间:2019-07-05 15:20:31

标签: java android variables android-recyclerview interface

每当我的AudioRecorder创建一个新文件时,我只是试图更新RecyclerView。我的recyclerview是在一个片段上创建的(我们称其为片段A)。我还有另一个片段,每当它被调用时,就开始记录音频(我们称之为片段B)。

我正在使用片段B中的接口来告知片段A适配器应该更新数据。

我已经使用“ UpdateData()”方法创建了一个公共接口。

当在片段B上按下“停止记录”按钮时,我正在调用接口,以便它可以与主要片段(片段A)进行通信并更新数据。

到目前为止,Android Studio告诉我,即使我在“附加条件”方法中定义了接口变量,该变量还是null。

[“ On Attach”方法上的上下文变量是指我的主要活动,而不是指recyclerview所在的当前片段。这是一个问题,所以我对其进行了更改,以便他获取片段。但是,它并没有阻止应用程序崩溃。

//Here's my main Fragment (Fragment A)
public class RecordsFragment extends Fragment implements Records_BottomSheet_Dialog.BottomSheet_Interface {
    private static final int PERMISSION_REQUEST = 1000;
    static ArrayList<String> mNames = new ArrayList<>();
    static ArrayList<String> NbFiles = new ArrayList<>();
    static ArrayList<String> PathFiles = new ArrayList<>();
    static int NumberFile= 0;
    static RecyclerView recyclerView;
    static RecyclerViewAdapter adapter;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_records, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //Check if we have the permission to read storage
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //We don't have the permission, so request it.
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST);
        }
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
            //We don't have the permission, so request it.
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSION_REQUEST);
        }
        //We already have permission
        else {
            permissionExists();
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        initRecyclerView(view, recyclerView, adapter);
            }

    @Override
    public void onResume() {
        super.onResume();
        ((FileAndDirectoryActivity) getActivity())
                .setButton("Créer un nouvel Enregistrement", true);
    }
    public void initRecyclerView(View v, RecyclerView recyclerView, RecyclerView.Adapter adapter) {
        recyclerView = v.findViewById(R.id.recyclerview);
        adapter = new RecyclerViewAdapter(mNames, getActivity().getApplicationContext());
        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
    }
    private void permissionExists() {
        mNames.clear();
        PathFiles.clear();
        NbFiles.clear();
        String path = Environment.getExternalStorageDirectory().toString() + "/Rapture";
        File directory = new File(path);
        boolean success = true;
        if (!directory.exists()) {
            success = directory.mkdirs();
        }
        if (success) {
            File[] arrayFiles = directory.listFiles();
            for (File file : arrayFiles) {
                mNames.add(file.getName());
                PathFiles.add(file.getPath());
                NbFiles.add(file.getName());
            }
        }
    }

    @Override
    public void UpdatetheData(boolean state) {
        if (state==true){
            adapter.notifyDataSetChanged();
        }

    }
}
//Here's my other fragment (the one that records upon called, Fragment B)
public class Records_BottomSheet_Dialog extends BottomSheetDialogFragment{
    private MediaRecorder AudioRecorder;
    private String outputFile;
    private FloatingActionButton stop;
    private static final int PERMISSION_REQUEST = 1000;
    private Integer FileSize = RecordsFragment.NbFiles.size();
    private BottomSheet_Interface bts;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        permissionExists();
        View view = inflater.inflate(R.layout.modal_records, container, false);
        FloatingActionButton stop_record = view.findViewById(R.id.stop);
        stop_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bts.UpdatetheData(true);
                AudioRecorder.stop();
                AudioRecorder.release();
                AudioRecorder = null;
                Toast.makeText(getActivity(), "Fin de l'enregistrement", Toast.LENGTH_SHORT).show();
                dismiss();
            }
        });
        return view;
    }
    public interface BottomSheet_Interface{
        void UpdatetheData(boolean state);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        try {
            bts = (BottomSheet_Interface) getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
        } catch (ClassCastException e){
            throw new ClassCastException(context.toString()
            +" must implement BottomSheet_Interface");
        }

    }

    private void permissionExists() {
        AudioRecorder = new MediaRecorder();
        AudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        AudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        if (FileSize != 0) {
            for (int i = 0; i < FileSize + 1; i++) {
                String path = Environment.getExternalStorageDirectory().toString() + "/Rapture/Recording(" + Integer.toString(i) + ").mp3";
                File f = new File(path);
                if (!f.exists()) {
                    AudioRecorder.setOutputFile(Environment.getExternalStorageDirectory().toString() + "/Rapture/Recording(" + Integer.toString(i) + ").mp3");
                    break;
                }
            }
        } else {
            AudioRecorder.setOutputFile(Environment.getExternalStorageDirectory().toString() + "/Rapture/Recording(0).mp3");
        }
        AudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
        Toast.makeText(getActivity(), "Enregistrement", Toast.LENGTH_SHORT).show();
        try {
            AudioRecorder.prepare();
            AudioRecorder.start();
        } catch (IllegalStateException ie) {

        } catch (IOException ioe) {

        }
    }

}

问题是当我使用AudioRecorder录制多个录音时,如果RecyclerView没有更新,则如果我重试,则应用程序崩溃。因此,每次用户停止记录时,我都需要更新RecyclerView适配器。

我希望RecyclerView直接显示创建的新文件,但我必须先导航到其他选项卡,然后再返回到音频选项卡以对其进行更新。

0 个答案:

没有答案