Make two different classes communicate

7

I'm making an Android application that uses time and date selectors (DatePicker and TimePicker), which are displayed in the form of fragments. When the user sets the desired time, I need it to be passed from the selector fragment to the main window. I have the following codes:

Time selector fragment:

package pickers;

import java.util.Calendar;

import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.text.format.DateFormat;

import compromissos.Tela_Cadastro;

public class TimePicker extends DialogFragment implements
        TimePickerDialog.OnTimeSetListener {

    public TimePicker() {
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    @Override
    public void onTimeSet(android.widget.TimePicker view, int hourOfDay,
            int minute) {
        // aqui que eu preciso que a hora selecionada seja enviada para a classe
        // princpal

    }

}

And the class that calls the time fragment:

package compromissos;

import pickers.TimePicker;
import android.app.ActionBar;
import android.app.Activity;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import classes.BancoDeDados;
import classes.Evento;

import com.bravosix.compromissos.R;

public class Tela_Cadastro extends Activity {

    BancoDeDados bd = new BancoDeDados(this);
    private EditText nome, data, local, telefone;

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

        nome = (EditText) findViewById(R.id.cadastro_input_evento);
        local = (EditText) findViewById(R.id.cadastro_input_local);
        data = (EditText) findViewById(R.id.cadastro_input_data);
        telefone = (EditText) findViewById(R.id.cadastro_input_telefone);

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_cadastro, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {

        switch (item.getItemId()) {

        case R.id.cadastrar:
            salvarEvento();
            return true;

        case R.id.cancelar:
            finish();
            return true;

        default:
            return super.onMenuItemSelected(featureId, item);
        }
    }

    public void mostrarDatePicker(View view) {
        DialogFragment newFragment = new TimePicker();
        newFragment.show(getFragmentManager(), "timePicker");
    }

    public void salvarEvento() {

        String evento_nome, evento_local, evento_data, evento_telefone;

        evento_nome = nome.getText().toString();
        evento_local = local.getText().toString();
        evento_data = data.getText().toString();
        evento_telefone = telefone.getText().toString();

        bd.adicionarEvento(new Evento(evento_nome, evento_local, evento_data,
                evento_telefone));

        Toast.makeText(this, "Evento criado com sucesso.", Toast.LENGTH_SHORT)
                .show();
        finish();
    }
}

I did some research but did not come up with any way that would allow me to do it in a simple way. I read that I could call a static method in the main class, but I need to do a toast, which requires context, which I could not get inside a static method. What do you suggest?

    
asked by anonymous 23.04.2014 / 20:21

1 answer

7

This is how I usually do it.

In the DialogFragment class I declare an interface that defines the methods that Activity , which calls Fragment , must implement to be notified of what happens in Fragment .

public interface TimeSetListener {
      public void onTimeSet(int hora, int minuto);
}  

I declare a field in DialogFragment to save the reference of Activity which calls Fragment .

TimeSetListener mListener;  

In event onAttach of DialogFragment I keep the Activity reference, it must implement the interface.

@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (TimeSetListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
            + " deve implementar TimeSetListener");
        }
    }  

When I want to inform Activity , I call its interface method.

@Override
public void onTimeSet(android.widget.TimePicker view, int hourOfDay,
        int minute) {
    mListener.onTimeSet(hourOfDay, minute);
}
    
23.04.2014 / 20:48