Hello! I have the following problem: A user register, inside an activity that has a ViewPager with 3 fragments that each collects specific user data to save them in the firebase. The idea is that when the user fills the data of the first fragment he stores the data and in the 3rd fragment save all of them in the firebase; For this I am trying to use interfaces according to the documentation of android, that when clicking on the button of one of the fragments it saves the data in the interface implemented by the activity and passes to the next fragment.
Interface
public interface InterfaceUsuario {
public String getId();
public String getApelido();
public String getNome();
public String getEmail();
public String getNascimento();
public String getGenero();
public String getCidade();
public String getEstado();
public String getPais();
public String getFotoPerfil();
public String getDenominacao();
public String getCargo();
public String getBatizado();
public String setId();
public String setApelido();
public String setNome();
public String setEmail();
public String setNascimento();
public String setGenero();
public String setCidade();
public String setEstado();
public String setPais();
public String setFotoPerfil();
public String setDenominacao();
public String setCargo();
public String setBatizado();
}
Activity that implements it:
public class LoginActivity extends AppCompatActivity implements InterfaceUsuario {
//ATRIBUTOS
public String idUsuario;
private static final int RC_SIGN_IN = 123;
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.FACEBOOK_PROVIDER).build());
private ViewPager viewPager;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//INSTANCIANDO OS COMPONENTES DO VIEW PAGER
viewPager = findViewById(R.id.view_pager);
CadastroAdapter adapter = new CadastroAdapter(getSupportFragmentManager());
adapter.adicionarFragment(new CadastroFragment1());
adapter.adicionarFragment(new CadastroFragment2());
adapter.adicionarFragment(new CadastroFragment3());
viewPager.setAdapter(adapter);
viewPager.setPageTransformer(true, new ZoomOutPageTransform());
viewPager.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return true;
}
});
//BUILDING FIREBASEUI SOLE INTENT
if (verificarLogin() == false){
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setLogo(R.drawable.hdt_logo)
//.setTheme(R.style.AppTheme)
.build(),
RC_SIGN_IN);
}
}
//VERIFICA SE O USUÁRIO JÁ ESTÁ LOGADO
private boolean verificarLogin() {
mAuth = ConfiguracaoFirebase.getFirebaseAuth();
if (mAuth.getCurrentUser() != null){
//valida se ele já está cadastrado e chama a proxima activity
return true;
} else {
return false;
}
}
//THE RESULT OF THE LOGIN FLOW IS DEALT WITH HERE
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN){
IdpResponse response = IdpResponse.fromResultIntent(data);
if (resultCode == RESULT_OK){
//SUCESS IN THE LOGIN
FirebaseUser user = mAuth.getCurrentUser();
idUsuario = user.getUid();
//SALVANDO OS DADOS DO USUÁRIO NO SHARED PREFERENCES
SharedPreferences preferences = new SharedPreferences(LoginActivity.this);
preferences.salvarUsuarioPreferences(user.getUid(), user.getDisplayName(), user.getEmail());
Toast.makeText(this, "Nome no preferences: "+ preferences.getCHAVE_NOME(), Toast.LENGTH_SHORT).show();
} else {
//SIGN FAILED
Toast.makeText(this, "Erro ao fazer Login, verifique sua conexão com a " +
"internet e tente novamente", Toast.LENGTH_SHORT).show();
}
}
}
public void logout(View view) {
AuthUI.getInstance()
.signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(LoginActivity.this, "Deslogado com sucesso!", Toast.LENGTH_SHORT).show();
}
});
}
public void changePageItem(int pageNumber){
viewPager.setCurrentItem(pageNumber);
}
public void salvarDadosUsuario(){
Usuario usuario = new Usuario();
//PASSANDO OS DADOS DA INTERFACE PARA O MODEL USUARIO
usuario.setId(idUsuario);
usuario.setNome(getNome());
usuario.setApelido(getApelido());
usuario.setEmail(getEmail());
usuario.setNascimento(getNascimento());
usuario.setGenero(getGenero());
usuario.setEstado(getEstado());
usuario.setCidade(getCidade());
usuario.setDenominacao(getDenominacao());
usuario.setCargo(getCargo());
usuario.setBatizado(getBatizado());
usuario.salvarUsuario();
}
/****************** METODOS DA INTERFACE DE COMUNICAÇÃO ENTRE OS 3 FRAGMENTS ********************/
@Override
public String getId() {
return null;
}
@Override
public String getApelido() {
return null;
}
@Override
public String getNome() {
return null;
}
@Override
public String getEmail() {
return null;
}
@Override
public String getNascimento() {
return null;
}
@Override
public String getGenero() {
return null;
}
@Override
public String getCidade() {
return null;
}
@Override
public String getEstado() {
return null;
}
@Override
public String getPais() {
return null;
}
@Override
public String getFotoPerfil() {
return null;
}
@Override
public String getDenominacao() {
return null;
}
@Override
public String getCargo() {
return null;
}
@Override
public String getBatizado() {
return null;
}
@Override
public String setId() {
return null;
}
@Override
public String setApelido() {
return null;
}
@Override
public String setNome() {
return null;
}
@Override
public String setEmail() {
return null;
}
@Override
public String setNascimento() {
return null;
}
@Override
public String setGenero() {
return null;
}
@Override
public String setCidade() {
return null;
}
@Override
public String setEstado() {
return null;
}
@Override
public String setPais() {
return null;
}
@Override
public String setFotoPerfil() {
return null;
}
@Override
public String setDenominacao() {
return null;
}
@Override
public String setCargo() {
return null;
}
@Override
public String setBatizado() {
return null;
}
}
Fragment1 (the others have a similar code)
public class CadastroFragment1 extends Fragment {
//ATRIBUTOS
private Button btContinuar;
private EditText etNome, etApelido, etEmail, etNascimento;
public CadastroFragment1() {
// Required empty public constructor
}
//DECLARAÇÃO DA INTERFACE DE COMUNICAÇÃO ENTRE ACTIVITY E FRAGMENTS
public interface InterfaceUsuario {
public String setNome(String nome);
public String setApelido(String apelido);
public String setEmail(String email);
public String setNascimento(String nascimento);
}
private InterfaceUsuario interfaceUsuario;
@Override
public void onAttach(Context context) {
super.onAttach(context);
try{
interfaceUsuario = (InterfaceUsuario) context;
} catch (ClassCastException e){
throw new ClassCastException(context.toString() + "must implement the nterface!");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ViewGroup viewGroup = (ViewGroup) inflater.inflate(
R.layout.fragment_cadastro1, container, false);
btContinuar = viewGroup.findViewById(R.id.bt_continuar1);
etNome = viewGroup.findViewById(R.id.et_nome);
etApelido = viewGroup.findViewById(R.id.et_apelido);
etEmail = viewGroup.findViewById(R.id.et_email);
etNascimento = viewGroup.findViewById(R.id.et_nascimetno);
//RECEBENDO OS DADOS DO USUÁRIO LOGADO
SharedPreferences preferences = new SharedPreferences(getActivity());
etNome.setText(preferences.getCHAVE_NOME());
etEmail.setText(preferences.getCHAVE_EMAIL());
btContinuar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (etNome.getText().toString().trim().equals("")
|| etApelido.getText().toString().trim().equals("")
|| etEmail.getText().toString().trim().equals("")
|| etNascimento.getText().toString().trim().equals("")){
Toast.makeText(getActivity(), "Tem que preencher", Toast.LENGTH_SHORT).show();
} else {
//SALVANDO AS INFORMAÇÕES NA NTERFACE DE COMUNICAÇÃO
interfaceUsuario.setApelido(etApelido.getText().toString());
interfaceUsuario.setEmail(etEmail.getText().toString());
interfaceUsuario.setNome(etNome.getText().toString());
interfaceUsuario.setNascimento(etNascimento.getText().toString());
((LoginActivity) getActivity()).changePageItem(1);
}
}
});
return viewGroup;
}
}
Model class where you have getters and setters and the save function
public class Usuario {
//ATRIBUTOS
private String id;
private String nome;
private String apelido;
private String email;
private String nascimento;
private String genero;
private String cidade;
private String estado;
private String fotoPerfil;
private String denominacao;
private String cargo;
private String batizado;
public Usuario(){
}
public void salvarUsuario(){
DatabaseReference reference = ConfiguracaoFirebase.getReference();
reference.child("USUARIOS").child(id).setValue(this);
}
I do not know if there is another way to share data between fragments, but with this attempt, as soon as the instantiation of activity studio returns me the following errors: java.lang.reflect.InvocationTargetException! and java.lang.ClassCastException: com.herdeiros.rafah.herdeiros.View.LoginActivity@9d0d5ef0must implement the nterface! I have never worked with java instefaces and so I believe that it has implemented incorrectly, but I do not know how to solve it. Thank you!