0

Hello i am new to fragments.. I have one main activity and two fragments in it. if i enter data in first fragment's editText , it is displayed on second Fragment's TextView.. If i enter the data and press submit button repeatedly, the data is changing in second fragment too.. but when i press back button, the application get closed. I want to display data that was previously entered by me in fragment when i press the back button

Here is the code:

FirstFragment extends Fragment {

    private OnFragmentInteractionListener mListener;
    private EditText inputName;
    private EditText inputPhone;
    private String userName;
    private String userPhone;

    public FirstFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_first, container, false);

        inputName = (EditText) view.findViewById(R.id.edit_text_name);
        inputPhone = (EditText) view.findViewById(R.id.edit_text_phone);
        TextView submit = (TextView) view.findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inputName.getText().toString().equals("")) {
                    Toast.makeText(getActivity(), "Name must be filled", Toast.LENGTH_LONG).show();
                    return;
                }
                else if(inputPhone.getText().toString().equals("")){
                    Toast.makeText(getActivity(),"please enter the phone number" , Toast.LENGTH_SHORT).show();
                    return;
                }
                userName = inputName.getText().toString();
                userPhone = inputPhone.getText().toString();
                onButtonPressed(userName, userPhone);
                inputName.setText("");
                inputPhone.setText("");
            }
        });
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(String nameContent, String phoneContent) {
        if (mListener != null) {
            mListener.onFragmentInteraction(nameContent, phoneContent);
        }
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(String nameContent, String phoneContent);
    }
}

SecondFragment extends Fragment {

    //private OnFragmentInteractionListener mListener;
    private TextView updateName;
    private TextView updatePhone;

    public SecondFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_second, container, false);
        updateName = (TextView)view.findViewById(R.id.text_view_name);
        updatePhone = (TextView)view.findViewById(R.id.text_view_phone);
        return view;
    }
    public void updateTextField(String name, String phone){
        updateName.setText(name);
        updatePhone.setText(phone);
        }
}


MainActivity extends AppCompatActivity implements FirstFragment.OnFragmentInteractionListener{

    private FragmentActivity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @Override
    public void onFragmentInteraction(String nameContent, String phoneContent) {
        SecondFragment secondFragment = (SecondFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_show);
        secondFragment.updateTextField(nameContent, phoneContent);

    }


    public FragmentActivity getActivity() {
        return activity;
    }
}


**fragment_first.xml**

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.seasiainfotech.singhjasmeet.passinfragments.views.MainActivity">

    <EditText
        android:id="@+id/edit_text_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/enter_name"
        android:inputType="text"
        android:paddingEnd="5dp"
        android:paddingStart="5dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintLeft_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.050" />

    <EditText
        android:id="@+id/edit_text_phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/enter_phone"
        app:layout_constraintTop_toBottomOf="@+id/edit_text_name"
        android:inputType="phone"
        android:paddingTop="25dp"
        android:paddingStart="5dp"
        android:paddingEnd="5dp"/>

    <TextView
        android:id="@+id/submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/edit_text_phone"
        android:layout_marginTop="50dp"
        android:padding="7dp"
        android:text="@string/sbmt"
        android:textSize="20sp"
        android:textColor="@color/colorAccent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:background="@drawable/button_stroke"/>



</android.support.constraint.ConstraintLayout>

**fragment_Second.xml**
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.seasiainfotech.singhjasmeet.passinfragments.views.MainActivity">

    <TextView
        android:id="@+id/text_view_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:textSize="30sp"
        android:textColor="@color/colorPrimaryDark"/>

    <TextView
        android:id="@+id/text_view_phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/text_view_name"
        android:textSize="20sp"
        android:padding="8dp"
        android:textColor="@color/colorPrimary"/>

</android.support.constraint.ConstraintLayout>

activity_main.xml

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.seasiainfotech.singhjasmeet.passinfragments.views.MainActivity">

    <fragment
        android:id="@+id/fragment_input"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:name="com.seasiainfotech.singhjasmeet.passinfragments.fragments.FirstFragment"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

    <fragment
        android:id="@+id/fragment_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:name="com.seasiainfotech.singhjasmeet.passinfragments.fragments.SecondFragment"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/fragment_input"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
MinnuKaAnae
  • 1,646
  • 3
  • 23
  • 35
  • 1
    check this answer to help you redefine back button behaviour: https://stackoverflow.com/questions/7992216/android-fragment-handle-back-button-press – Amine ABDALKHALKI Mar 20 '18 at 10:00
  • logcat please post – IntelliJ Amiya Mar 20 '18 at 10:02
  • i would suggest you to use mvvm approach with data binding , and use fragment backstack . you will get the exact results you want. adding fragmnet to backstack wil help your back button probelm and mvvm's viewmodel will help to retain the data and fill the fields with the help of data binding – Adeel Turk Mar 20 '18 at 10:19

3 Answers3

0

override onBackPressed method.

@Override
public void onBackPressed()
{
super.onBackPressed();// remove this line
...
//enter your code here.
}

and add this code.

getSupportFragmentManger().
beginTransaction().
replace().
addToBackStack().
.commit();
Pinky
  • 1
  • 4
0

Override "onBackPressed" method in MainActivity

 @Override
public void onBackPressed()
{
  if(want_to_close_the_app){
//call super
  super.onBackPressed();
}
else{
// dont call super
}

}

Anand
  • 51
  • 6
0

Give your fragments tags while adding them. Ex. Tag for FirstFragment is "firstFragment" and tag for SecondFragment is "secondFragment". Take a common String variable called current fragment in your activity and change it while adding fragment.

public class MainActivity extends Activity{
    public static String currentFragment = null;
    //while adding first fragment
    currentFragment = "firstFragment";

    //while adding second fragment
    currentFragment = "firstFragment";
}

Now override onBackPressed in your activity as below.

@Override
public void onBackPressed() {
    if(currentFragment.equals("secondFragment"){
        //load first fragment
    }else{
        super.onBackPressed();
    }
}
Megha Maniar
  • 444
  • 5
  • 22