Problems when passing a data from an EditText in a fragment to a TextView in another fragment

1

I have a fragment that contains an EditText where the user will enter his name.

In another fragment is the TextView that will get the name you typed in fragment .

Fragment Edit (where the user will type the name):

public class Editar extends Fragment implements View.OnClickListener{ 
    private EditText editar; private Button okBotao;

    View rootview;

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
        rootview = inflater.inflate(R.layout.fragment_editar, container, false);

        editar = (EditText) rootview.findViewById(R.id.editar); 
        okBotao = (Button) getActivity().findViewById(R.id.ok);

        okBotao.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) { 
                InicioActivity menu = new InicioActivity(); 
                Bundle args = new Bundle(); 
                args.putString("editar", String.valueOf(editar));    
                menu.setArguments(args); 
            } 
         }); 
         return rootview;
    }
}

Fragment Home (where the name will be displayed):

public class Inicio extends Fragment { 
    TextView text; 
    View rootview;

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
        rootview = inflater.inflate(R.layout.fragment_main, container, false);

        TextView text = (TextView)getView().findViewById(R.id.campoNome);
        String editar = getArguments().getString("editar"); 
        text.setText(editar);

        return rootview; 
    }
}

In my application I use Navigation Drawer .

    
asked by anonymous 14.04.2015 / 06:47

1 answer

1

The problem is in the way you try to get the EditText string.

String.valueOf(editar)  

The String.valueOf() method returns the string representation of the passed value as argument. It is typically used to convert numeric values to string .
When used with an Object , as is the case here, it is the equivalent of calling the object.toString() method.

Usually what object.toString() returns is not what we're expecting. So if you use editar.toString(); you will not get the EditText text.

What's inside an EditText is not a string but an Editable containing the text entered in the EditBox .
To access this text we must first get the Editable , using the method getText() , and then get the string with toString() :

editar.getText().toString();  

You should change the line:

args.putString("editar", String.valueOf(editar));

for

args.putString("editar", editar.getText().toString()); 
    
14.04.2015 / 12:27