2

java & Two.java) into each fragments there's editext: One : editText_One Two : editText_Two

How to save and resotre editText_One (and editText_Two), when i switch between fragments?

I've tried several things after reading tutos, but nothing working well ;(

One.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_one"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="one" />

    <EditText
        android:layout_width="237dp"
        android:layout_height="wrap_content"
        android:inputType="date"
        android:ems="10"
        android:id="@+id/editText_One"
        android:text="blabla"
        android:layout_gravity="center_horizontal" />

</LinearLayout>

Two.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_one"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TWO" />

    <EditText
        android:layout_width="237dp"
        android:layout_height="wrap_content"
        android:inputT`enter code here`ype="date"
        android:ems="10"
        android:id="@+id/editText_Two"
        android:layout_gravity="center_horizontal" />

One.java :

/**
 * 
 */
package com.example.navigationsubmenu;

/**
 * @author info-medios
 *
 */
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Calendar;

public class One extends Fragment {
//    public static final String EXTRA_URL_nommatiere = "url";
    EditText editText_one;
//    String valeur;
    private  final String PERSISTENT_VARIABLE_BUNDLE_KEY = "persistentVariable";

    public One() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Bundle bundle = new Bundle();
/*        Bundle bundle = getActivity().getIntent().getExtras();
        Bundle mySavedInstanceState = getArguments();

        if (bundle!= null) {// to avoid the NullPointerException
            // editText_one.setText("premiere");
            String persistentVariable = mySavedInstanceState.getString(PERSISTENT_VARIABLE_BUNDLE_KEY);
            editText_one.setText(persistentVariable);
        }*/
        Bundle extras = getActivity().getIntent().getExtras();
        if (extras != null) {
            String persistentVariable = extras.getString(PERSISTENT_VARIABLE_BUNDLE_KEY);
            editText_one.setText(persistentVariable);

        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.one, container, false);
        //Instancier vos composants graphique ici (faîtes vos findViewById)
        editText_one = (EditText) view.findViewById(R.id.editText_One);             //getview marche aussi





/*        Bundle extras = getActivity().getIntent().getExtras();
        if (extras != null) {
            valeur = extras.getString(EXTRA_URL_nommatiere);                        //Affiche le nom matiere
        }
        else
        {

        }
        editText_one.setText(valeur );*/


        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
        String persistentVariable = editText_one.getText().toString();

        Intent intent = new Intent(getActivity(), One.class);
        intent.putExtra(persistentVariable, PERSISTENT_VARIABLE_BUNDLE_KEY);
        //startActivity(intent);

        getArguments().putString(persistentVariable, PERSISTENT_VARIABLE_BUNDLE_KEY);
    }

/*    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Bundle extras = getActivity().getIntent().getExtras();
        if (savedInstanceState != null) {
            // Restore last state for checked position.
            valeur = extras.getString(EXTRA_URL_nommatiere);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putString("TEXT", valeur);

    }*/

/*    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.v(TAG, "Inside of onRestoreInstanceState");
        valeur = extras.getString(EXTRA_URL_nommatiere);
    }*/

}

Can someone can help me please,

many thnaks

Cumbayah
  • 4,415
  • 1
  • 25
  • 32
morbak
  • 317
  • 4
  • 17

2 Answers2

0

First you need to attach the fragments to activity then you can simply define two strings String one ,String two in the activity containing the fragments and assign the value of each editText to diffrent one i.e

String one=editTextOne.getText.toString();
String two=editTextTwo.getText.toString();
Radwa
  • 325
  • 4
  • 21
  • Have you an exemple somewhere? – morbak Jun 26 '16 at 15:25
  • http://stackoverflow.com/questions/17580593/android-two-fragments-in-same-activity – Radwa Jun 28 '16 at 10:24
  • the one, two should be global variables in the activity means define out of the any method i.e you define the String one="",String two=""; and assign it when you attach each fragment : one=editTextOne.getText.toString(); two=editTextTwo.getText.toString(); you can use Shared Preferences too. – Radwa Jun 28 '16 at 10:31
0

When you have to switch between either activities or fragments, you can use Shared Preferences to store a small amount of datas and retrieve them.

Shared Prefs are small sets of key/value pairs.

Write

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

SharedPreferences.Editor editor = sharedPref.();

              editor.putInt(getString(R.string.saved_high_score), newHighScore);

editor.commit();

Read

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

int defaultValue = getResources().getInteger(R.string.saved_high_score_default);

long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

You can write and read any primitive data types such as Strings using put[Type] and get[Type] methods.

Source codes above come from the official android developer training and belongs to Android.

"is there a way with saveInstanceState ?"

I think this bundle is usefull when one activity is destroyed and created by Screen rotation or resumed after a call, but not when switching between activities and fragments.

But you can try it. I know that views like EditText with id have a built-in saveInstanceState so you do not have to handle it manually.

To switch between fragments you can use activity class scoped properties. You will need to add interfaces to your fragments to allow them to communicate with the activity.

EXAMPLE

Overview

The following example shows how to switch between fragments and keep EditText values.

The MainActivity contains a FrameLayout and two buttons. The fragment transaction is done on button click events.

Fragments include an interface to communicate with the activity. Each time the EditText value is changed, the activity's property is updated.

The activity communicates with the fragment to set EditText value right after the transaction.

First of all, here are xml layouts files for the MainActivity, the FragmentA and the FragmentB classes :

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="100"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="morbak.stackoverflow.fragmentcommunication.MainActivity">

    <FrameLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="50"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="50"
        android:orientation="horizontal"
        android:weightSum="100">

        <Button
            android:id="@+id/button1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="50"
            android:text="Fragment A" />

        <Button
            android:id="@+id/button2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="50"
            android:text="Fragment B" />

    </LinearLayout>

</LinearLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/etOne"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Fragment A content"/>

</LinearLayout>

fragment_a.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/etTwo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Fragment B content"/>

</LinearLayout>

fragment_b.xml

Then, here are Fragments A and B classes. Source code is self explanatory.

package morbak.stackoverflow.fragmentcommunication;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

public class FragmentA extends Fragment {

    //Views
    EditText etOne;

    //Fields
    String value;

    //Listeners
    OnFragmentASelectedListener mCallback;

    //Context
    Context context;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        //Inflate views and layouts
        View rootView = inflater.inflate(R.layout.fragment_a, container, false);

        etOne = (EditText) rootView.findViewById(R.id.etOne);

        //Events
        etOne.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                //Execute the interface's abstract method
                mCallback.onFragmentASelected(s.toString());

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        etOne.setText(value);

        return rootView;
    }

    //Set the fragment's field value
    public void setEditText(String newValue) {

        value = newValue;

    }

    //Interface
    public interface OnFragmentASelectedListener {
        public void onFragmentASelected(String value);
    }

    //Throws an exception if the activity implements FragmentA.OnFragmentASelectedListener, but not the abstract method
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        context = activity;

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnFragmentASelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentASelectedListener");
        }
    }
}

FragmentA.java

The same work should be done with FragmentB, but you obviously have to search and replace FragmentA to FragmentB and etOne to etTwo.

Finally, here is the MainActivity who handles fragment transactions and uses fragments' listeners :

package morbak.stackoverflow.fragmentcommunication;

import android.content.Context;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements FragmentA.OnFragmentASelectedListener, FragmentB.OnFragmentBSelectedListener {

    Button button1;
    Button button2;

    FragmentTransaction transaction;
    FragmentA fragmentA;
    FragmentB fragmentB;

    String editTextOne;
    String editTextTwo;

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

        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);

        editTextOne = "";
        editTextTwo = "";

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                transaction = getSupportFragmentManager().beginTransaction();

                fragmentA = new FragmentA();

                transaction.replace(R.id.fragment_container, fragmentA);
                transaction.addToBackStack(null);
                transaction.commit();

                fragmentA.setEditText(editTextOne);

            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                transaction = getSupportFragmentManager().beginTransaction();

                fragmentB = new FragmentB();

                transaction.replace(R.id.fragment_container, fragmentB);
                transaction.addToBackStack(null);
                transaction.commit();

                fragmentB.setEditText(editTextTwo);

            }
        });
    }

    public void onFragmentASelected(String value) {
        editTextOne = value;
    }

    public void onFragmentBSelected(String value) {
        editTextTwo = value;
    }
}

MainActivity.java

Alexandre Martin
  • 1,472
  • 5
  • 14
  • 27
  • OK it's working with sharedpreferences but it's not really made for that. There isn't a solution with _Bundle savedInstanceState_ ? – morbak Jun 27 '16 at 10:49