Home > front end >  Showing dialog inside fragment and getSupportFragmentManager() not working
Showing dialog inside fragment and getSupportFragmentManager() not working

Time:10-02

In main activity is a dashboard and have tablayout & viewpager, and have icon menu to click and working well, but the problem is when showing dialog inside fragment. If showing dialog not in fragment (normal activity) the code working well, but my code not working well inside fragment. I was tried many suggestion from this forum but still don't how to fix this issue.

Here's the code for my Fragment:

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

public class ScanTabFragment extends Fragment implements View.OnClickListener, ProjectDialogActivity.DialogListener{

private CardView cardViewCreateProjectBatch;
private View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        view = inflater.inflate(R.layout.fragment_scan_tab, container, false);
        cardViewCreateProjectBatch = view.findViewById(R.id.cardViewCreateProjectBatch);
        cardViewCreateProjectBatch.setOnClickListener(this);

        return view;

    }

    @Override
    public void onClick(View view) {
        Intent i;

        switch (view.getId()) {
                case R.id.cardViewCreateProjectBatch:
                newProjectDialog();
                break;
        }
    }

 private void newProjectDialog() {
     

        String projectNameAuto;
        projectNameAuto = "PJ-Batch-"   android.text.format.DateFormat.format("yyyy.MM.dd.kk.mm.ss", new java.util.Date());
        FragmentManager fm = getSupportFragmentManager(); //this not working in fragment but working in normal activity (not fragment) and i have tried other code like this below but app crashed and dialog not show
        
        //FragmentManager fm = getActivity().getSupportFragmentManager();
        //FragmentManager fm = getActivity().getSupportFragmentManager();
        //FragmentManager fm = this.getParentFragment().getChildFragmentManager();
        //FragmentManager fm = this.getParentFragment().getFragmentManager();
        //FragmentManager fm = this.getParentFragment().getFragmentManager().beginTransaction();
        //FragmentManager fm = this.getChildFragmentManager();
        //FragmentManager fm = getFragmentManager();
        //FragmentManager fm = getParentFragment();

        ProjectDialogActivity alertDialog = ProjectDialogActivity.newInstance("Create New Batch Project", projectNameAuto, "");
        alertDialog.setCancelable(false);
        alertDialog.show(fm, "fragment_alert");

        ProjectDialogActivity alertDialog = ProjectDialogActivity.newInstance("Create New Batch Project", projectNameAuto, "");
        alertDialog.setCancelable(false);
        alertDialog.show(fm, "fragment_alert");
        }

public long insertProject1(String project_name, String created_date, Integer status, String notes) {

        mySQLiteAdapterBatch = new DatabaseHelperBatch(view.getContext());
        SQLiteDatabase db = mySQLiteAdapterBatch.getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        contentValues.put("project_name", project_name);
        contentValues.put("created_date", created_date);
        contentValues.put("status", status);
        contentValues.put("notes", notes);

        return db.insert("project1", null, contentValues);
    }

public long insertProject2(String project_name, String created_date, Integer status, String notes) {

        mySQLiteAdapterBatch = new DatabaseHelperBatch(view.getContext());
        SQLiteDatabase db = mySQLiteAdapterBatch.getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        contentValues.put("project_name", project_name);
        contentValues.put("created_date", created_date);
        contentValues.put("status", status);
        contentValues.put("notes", notes);

        return db.insert("project2", null, contentValues);
    }

 @Override
    public void applyTexts(String project_name, String created_date, Integer status, String notes) {
        if (ProjectDialogActivity.radioButtonProject1.isChecked() == true) {
            insertProject1(project_name, created_date, status, notes);
            Toast.makeText(view.getContext(), "New Batch project1 has been created", Toast.LENGTH_LONG).show();
            ;
        }

        if (ProjectDialogActivity.radioButtonProject2.isChecked() == true) {
            insertProject2(project_name, created_date, status, notes);
            Toast.makeText(view.getContext(), "New Batch project2 has been created", Toast.LENGTH_LONG).show();
        }

    }
}

Here's the code for the Dialog Fragment:

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatDialogFragment;
public class ProjectDialogActivity extends AppCompatDialogFragment {
    //Variables
    private String projectName;
    private String projectCreated;
    private String projectNotes;
    private Integer projectStatus;

    private TextView textViewProjectName;
    private TextView textViewNotes;

    public static RadioButton radioButtonProject1;
    public static RadioButton radioButtonProject2;

    public static ProjectDialogActivity newInstance(String title, String getProjectName, String getNotes) {
        ProjectDialogActivity frag = new ProjectDialogActivity();
        Bundle args = new Bundle();
        args.putString("title", title);
        args.putString("inputProjectName", getProjectName);
        args.putString("inputNotes", getNotes);
        frag.setArguments(args);
        return frag;
    }

    private ProjectDialogActivity.DialogListener listener;
    //private EditText editTextRack;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        String title = getArguments().getString("title");
        String inputProjectName = getArguments().getString("inputProjectName");
        String inputNotes = getArguments().getString("inputNotes");


        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        final View view = inflater.inflate(R.layout.activity_projectdialog, null);

        radioButtonProject1 = view.findViewById(R.id.radioButtonScan1);
        radioButtonProject2 = view.findViewById(R.id.radioButtonScan2);

        textViewProjectName = view.findViewById(R.id.editTextProjectName);
        textViewNotes = view.findViewById(R.id.editTextNotes);

        textViewProjectName.setSingleLine(true);
        textViewNotes.setSingleLine(true);

        textViewProjectName.setText(inputProjectName);
        textViewNotes.setText(inputNotes);

        projectName = textViewProjectName.getText().toString();

        builder.setView(view)
                .setTitle(title)
                //.setView(input)
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialoginterface, int i) {
                        dialoginterface.cancel();
                    }
                })
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //String Rack = editTextRack.getText().toString();
                        //String projectName = textProject.getText().toString();

                        ////listener.applyTexts(textProject.getText().toString(), itemfrloc, itemtoloc, textNotes.getText().toString());

                        //String answer="OK";
                        //listener.applyOK_insert(answer);

                    }
                });
        return builder.create();

    }

    @Override
    public void onResume() {
        super.onResume();
        final AlertDialog d = (AlertDialog) getDialog();
        if (d != null) {
            Button positiveButton = (Button) d.getButton(Dialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    projectName = textViewProjectName.getText().toString();
                    projectCreated = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
                    projectStatus = 0;
                    projectNotes = textViewNotes.getText().toString();
                    Boolean wantToCloseDialog;
                    //Do stuff, possibly set wantToCloseDialog to true then...
                    if (projectName.isEmpty()) {
                        Toast.makeText(getContext(), "Cannot left blank, Please input your project name", Toast.LENGTH_LONG).show();
                        textViewProjectName.requestFocus();
                        wantToCloseDialog = false;
                    } else {
                        wantToCloseDialog = true;
                    }

                    if (wantToCloseDialog == true) {
                        listener.applyTexts(projectName, projectCreated, projectStatus, projectNotes);
                        d.dismiss();
                    }
                    //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
                }
            });
        }
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        try {
            listener = (ProjectDialogActivity.DialogListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()   " must implement DialogListener");
        }
    }

    public interface DialogListener {
        // This is called when the dialog is completed and the results have been passed
        void applyTexts(String project_name, String created_date, Integer status, String Notes);
    }
}

CodePudding user response:

please try getParentFragmentManager() or getFragmentManager()

CodePudding user response:

The App crashed/stopped not because Fragment Manager, So if write:

FragmentManager fm = getActivity().getSupportFragmentManager(); \\OK or Use FragmentManager fm = getFragmentManager();  

then below that, write:

ProjectDialogActivity alertDialog = ProjectDialogActivity.newInstance("Create New Batch Project", projectNameAuto, "");
alertDialog.setTargetFragment(ScanTabFragment.this, 0); \\Your Tab Fragment Name
alertDialog.setCancelable(false);
alertDialog.show(fm, null);

and in other class: public class ProjectDialogActivity extends AppCompatDialogFragment, not need to write listener onAttach or onAttachFragment but write listener in this one:

@Override
    public void onResume() {
        super.onResume();
        final AlertDialog d = (AlertDialog) getDialog();
        if (d != null) {
            Button positiveButton = (Button) d.getButton(Dialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    projectName = textViewProjectName.getText().toString();
                    projectCreated = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
                    projectStatus = 0;
                    projectNotes = textViewNotes.getText().toString();
                    Boolean wantToCloseDialog;
                    //Do stuff, possibly set wantToCloseDialog to true then...
                    if (projectName.isEmpty()) {
                        Toast.makeText(getContext(), "Cannot left blank, Please input your project name", Toast.LENGTH_LONG).show();
                        textViewProjectName.requestFocus();
                        wantToCloseDialog = false;
                    } else {
                        wantToCloseDialog = true;
                    }

                    if (wantToCloseDialog == true) {
\\write listener in here
                        DialogListener listener = (DialogListener) getTargetFragment();
                        listener.applyTexts(projectName, projectCreated, projectStatus, projectNotes);
                        d.dismiss();
                    }
                    //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
                }
            });
        }
    }

 public interface DialogListener {
        // This is called when the dialog is completed and the results have been passed
        void applyTexts(String project_name, String created_date, Integer status, String Notes);

    }

the first time i thought of this problem because of Fragment Manager, don't know the right code how to calling fragment manager inside fragment, the other users also giving a some clue how to called the right way for fragment manager but still error because the listener is null that's why the error happened.

  • Related