first commit
This commit is contained in:
134
app/src/main/java/com/example/pap/RegisterActivity.java
Normal file
134
app/src/main/java/com/example/pap/RegisterActivity.java
Normal file
@@ -0,0 +1,134 @@
|
||||
package com.example.pap;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.EditText;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
import retrofit2.Call;
|
||||
import retrofit2.Callback;
|
||||
import retrofit2.Response;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
|
||||
public class RegisterActivity extends AppCompatActivity {
|
||||
|
||||
private EditText etRegNome, etRegEmail, etRegPassword, etRegAltura, etRegPeso;
|
||||
private Button btnRegister;
|
||||
private TextView tvGoToLogin;
|
||||
private SupabaseApi api;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_register);
|
||||
|
||||
// 1. Ligar os elementos do design ao código
|
||||
etRegNome = findViewById(R.id.etRegNome);
|
||||
etRegEmail = findViewById(R.id.etRegEmail);
|
||||
etRegPassword = findViewById(R.id.etRegPassword);
|
||||
etRegAltura = findViewById(R.id.etRegAltura);
|
||||
etRegPeso = findViewById(R.id.etRegPeso);
|
||||
btnRegister = findViewById(R.id.btnRegister);
|
||||
tvGoToLogin = findViewById(R.id.tvGoToLogin);
|
||||
|
||||
// 2. Configurar o Retrofit (A ponte de comunicação com o Supabase)
|
||||
Retrofit retrofit = new Retrofit.Builder()
|
||||
.baseUrl(SupabaseConfig.URL)
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.build();
|
||||
api = retrofit.create(SupabaseApi.class);
|
||||
|
||||
// 3. Configurar os cliques dos botões
|
||||
btnRegister.setOnClickListener(v -> efetuarRegisto());
|
||||
tvGoToLogin.setOnClickListener(v -> finish());
|
||||
}
|
||||
|
||||
private void efetuarRegisto() {
|
||||
String nome = etRegNome.getText().toString().trim();
|
||||
String email = etRegEmail.getText().toString().trim();
|
||||
String password = etRegPassword.getText().toString().trim();
|
||||
String pesoStr = etRegPeso.getText().toString().trim();
|
||||
String alturaStr = etRegAltura.getText().toString().trim();
|
||||
|
||||
// Verificações para garantir que o utilizador preencheu tudo
|
||||
if (nome.isEmpty() || email.isEmpty() || password.isEmpty() || pesoStr.isEmpty() || alturaStr.isEmpty()) {
|
||||
Toast.makeText(this, "Preencha todos os campos!", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
|
||||
if (password.length() < 6) {
|
||||
Toast.makeText(this, "A password precisa de pelo menos 6 caracteres.", Toast.LENGTH_SHORT).show();
|
||||
return;
|
||||
}
|
||||
|
||||
float peso = Float.parseFloat(pesoStr);
|
||||
float altura = Float.parseFloat(alturaStr);
|
||||
|
||||
// FASE 1: Criar a conta (Email e Password) no Supabase Auth
|
||||
UserCredentials credentials = new UserCredentials(email, password);
|
||||
|
||||
api.signUp(SupabaseConfig.API_KEY, credentials).enqueue(new Callback<SupabaseResponse>() {
|
||||
@Override
|
||||
public void onResponse(Call<SupabaseResponse> call, Response<SupabaseResponse> response) {
|
||||
if (response.isSuccessful() && response.body() != null) {
|
||||
|
||||
// Sucesso! A conta foi criada. Vamos extrair o ID e o Token
|
||||
String userId = response.body().id != null ? response.body().id : response.body().user.id;
|
||||
String token = "Bearer " + response.body().access_token;
|
||||
|
||||
// FASE 2: Guardar o Nome, Peso e Altura na tabela "profiles"
|
||||
salvarPerfil(userId, nome, email, peso, altura, token);
|
||||
|
||||
} else {
|
||||
String urlQueFalhou = response.raw().request().url().toString();
|
||||
if (response.code() == 400) {
|
||||
Toast.makeText(RegisterActivity.this, "Erro 400: Este email já existe ou a password é fraca.", Toast.LENGTH_LONG).show();
|
||||
} else {
|
||||
Toast.makeText(RegisterActivity.this, "Erro " + response.code() + " no Auth! Link: " + urlQueFalhou, Toast.LENGTH_LONG).show();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call<SupabaseResponse> call, Throwable t) {
|
||||
Toast.makeText(RegisterActivity.this, "Falha de rede (Sem internet?): " + t.getMessage(), Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Método responsável por guardar os dados extras na tabela profiles
|
||||
private void salvarPerfil(String id, String nome, String email, float peso, float altura, String token) {
|
||||
ProfileData profile = new ProfileData(id, nome, email, peso, altura);
|
||||
|
||||
api.insertProfile(SupabaseConfig.API_KEY, token, "application/json", "return=minimal", profile)
|
||||
.enqueue(new Callback<Void>() {
|
||||
@Override
|
||||
public void onResponse(Call<Void> call, Response<Void> response) {
|
||||
if (response.isSuccessful()) {
|
||||
// TUDO CORREU BEM!
|
||||
Toast.makeText(RegisterActivity.this, "Conta e Perfil criados com sucesso!", Toast.LENGTH_LONG).show();
|
||||
finish(); // Volta para o ecrã de login
|
||||
} else {
|
||||
// DEU ERRO A GUARDAR O PESO E ALTURA. VAMOS LER O ERRO EXATO!
|
||||
try {
|
||||
String erroExato = response.errorBody().string();
|
||||
// Esta mensagem vai mostrar-te o que está mal configurado no painel do Supabase
|
||||
Toast.makeText(RegisterActivity.this, "ERRO DA BASE DE DADOS: " + erroExato, Toast.LENGTH_LONG).show();
|
||||
} catch (Exception e) {
|
||||
Toast.makeText(RegisterActivity.this, "Erro a ler a resposta da base de dados.", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call<Void> call, Throwable t) {
|
||||
Toast.makeText(RegisterActivity.this, "Erro ao conectar à base de dados.", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user