Pass data from activity to fragments [closed]

0

I am trying to pass a data from a Activity to a Fragment , this must happen when I press a button. I tried with Bundle or directly with get and it happens to me is a predefined data, but when editing the text field and joining the button nothing is sent. I already tried by means of: 'Bundles', 'Direct', 'Interfaces'. It is important to note that the "Fragment" is in an "Activity" different from the other "Activity". Could you help me try to solve this?

Activity A:

public class MenuActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
//Esta es la Actividad principal, desde aqui se llama al fragment.
DrawerLayout drawerLayout;
NavigationView navigationView;
TextView txtIndice;
String Phone = "111-11-111-1";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    //Aqui uso el boton flotante para abrir una clase.
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(view.getContext(), Comentario.class);
            startActivity(intent);
        }
    });
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawerLayout.setDrawerListener(toggle);
    toggle.syncState();

    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

It's called the Fragment from Activity A:

 @Override
public boolean onNavigationItemSelected(MenuItem item) {

    android.app.FragmentManager fm1 = getFragmentManager();
    android.app.FragmentManager fm2 = getFragmentManager();
    LinearLayout ly;
    LinearLayout ly2;
    switch (item.getItemId()) {

        case R.id.pizza:
            ly = (LinearLayout) findViewById(R.id.izquierda);
            ly.removeAllViews();
            fm1.beginTransaction().replace(R.id.izquierda, new FragmentPizza()).commit();
            //FreagmentPedido es a donde debe llegar el texto de la ActivityB
            //Aqui invoco al fragmet
            ly2 = (LinearLayout) findViewById(R.id.derecha);
            ly2.removeAllViews();
            fm2.beginTransaction().replace(R.id.derecha, new FragmentPedido()).commit();

            drawerLayout.closeDrawer(GravityCompat.START);
            return true;
         } 
     return false; 
     }
 }

Activity B:

public class Comentario  extends AppCompatActivity  {
String datoFragment;
EditText comentario;
Button Enviar;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.comentario_flotante);
    comentario = (EditText)findViewById(R.id.Comen);
    Enviar = (Button)findViewById(R.id.enviar_comentario);
    Enviar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

         }
     });
  }
}

Fragment:

public class FragmentPedido extends Fragment implements View.OnClickListener {

View myview;
Button test1;
TextView recibirComentario;
String recibeDato;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    myview = inflater.inflate(R.layout.activity_fragment_pedido, container, false);
    test1 = (Button) myview.findViewById(R.id.pedir);
    recibirComentario = (TextView) myview.findViewById(R.id.recibe_comentario);
    return myview;
}

@Override
public void onClick(View v) {
    FragmentManager fm1 = getFragmentManager();
    switch (v.getId()) {
        case R.id.pedir:

        }
   }
}
    
asked by Daniel Eslava 07.05.2017 в 02:01
source

2 answers

4

Hello! Given the absence of code to more or less visualize the specific problem you have, I will describe the simplest method to pass data between components of your application using Bundle .

In your particular case, you want to pass information from the text field of a Activity (via a button) to another activity that manages the Fragment where you want to display the information from your first activity.

Since your first activity ( ActivityA in this example):

@Override
protected void onCreate(Bundle savedInstanceState) {

    //...

    Button button = (Button) findViewById(R.id.button_id);

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Una vez receptemos el evento, usaremos Bundle e Intent para pasar datos de una Activity a otra
            // Inicializas el Bundle
            Bundle bundle = new Bundle();

            // Inicializas el Intent
            Intent intent = new Intent(v.getContext(), ActivityB.class);

            // Información del EditText
            EditText editText = (EditText) findViewById(R.id.editText);
            String texto = editText.getText().toString();

            // Agregas la información del EditText al Bundle
            bundle.putString("textFromActivityA", texto);
            // Agregas el Bundle al Intent e inicias ActivityB
            intent.putExtras(bundle);
            startActivity(intent);
        }
    });

    // ...

}    

In the second activity ( ActivityB in this example), in the onCreate() method, you must use the "textFromActivityA" key that you previously defined about the incoming Bundle (you get it from Intent ) in order to obtain the String that you require, and so use it in other parts of your activity. In this way:

@Override
protected void onCreate(Bundle savedInstanceState) {

    // ... 

    // Obtienes el Bundle del Intent
    Bundle bundle = getIntent().getExtras();

    // Obtienes el texto
    String texto = bundle.getString("textFromActivityA");

    // Creamos un nuevo Bundle
    Bundle args = new Bundle();

    // Colocamos el String
    args.putString("textFromActivityB", texto);

    // Supongamos que tu Fragment se llama TestFragment. Colocamos este nuevo Bundle como argumento en el fragmento.
    TestFragment newFragment = new TestFragment();
    newFragment.setArguments(args);

    //Una vez haz creado tu instancia de TestFragment y colocado el Bundle entre sus argumentos, usas el FragmentManager para iniciarla desde tu segunda actividad.
    FragmentManager fm = getFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    fragmentTransaction.replace(R.id.fragmentContainer_id, newFragment); //donde fragmentContainer_id es el ID del FrameLayout donde tu Fragment está contenido.
    fragmentTransaction.commit();

    // ...

}

Then, in the method onCreateView() of Fragment :

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

    //Primero inflamos la vista del Fragment para que podamos acceder a los elementos propios del layout donde quisieras mostrar los datos que le llegan al Fragment.
    View v = inflater.inflate(R.layout.fragmentLayout, container, false); //donde fragmentLayout es la referencia a tu archivo XML con el layout del Fragment.

    String texto = getArguments().getString("textFromActivityB");

    //...

    return v;
}

Assuming you have correctly attached the references of your elements (in this case your Button and EditText ), you should not have problems.

I recommend that you review this link that describes in more detail the process of communication between components: link .

    
answered by 07.05.2017 в 03:08
0

If you do not want to use a Bundle , you can access the Activity that contains your Fragment .

  • With Fragment#getActivity() you can access the activity that contains your fragment.
  • If you access the activity in Fragment#onActivityCreated(Bundle savedState) you can be sure that the creation of your activity is already finished.

Example in your fragment:

@Override
public onActivityCreated(Bundle savedState){
    String cadena = getActivity().mStringCadenaEnActivity;
    // ahora puedes trabajar con el dato leido de un campo de la actividad
}
    
answered by 07.05.2017 в 03:18