Files
PAP/app/src/main/java/com/example/pap/LoginActivity.java

86 lines
3.5 KiB
Java

package com.example.pap;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
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;
public class LoginActivity extends AppCompatActivity {
private EditText etLoginEmail, etLoginPassword;
private Button btnLogin;
private TextView tvGoToRegister;
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Ligar o código aos IDs do ecrã
etLoginEmail = findViewById(R.id.etLoginEmail);
etLoginPassword = findViewById(R.id.etLoginPassword);
btnLogin = findViewById(R.id.btnLogin);
tvGoToRegister = findViewById(R.id.tvGoToRegister);
// Iniciar a memória do telemóvel
sharedPreferences = getSharedPreferences("MeusDadosApp", MODE_PRIVATE);
// Enviar para o Registo
tvGoToRegister.setOnClickListener(v -> {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
});
// Botão de Entrar
btnLogin.setOnClickListener(v -> {
String email = etLoginEmail.getText().toString().trim();
String password = etLoginPassword.getText().toString().trim();
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(this, "Preenche o email e a password!", Toast.LENGTH_SHORT).show();
return;
}
UserCredentials credentials = new UserCredentials(email, password);
SupabaseApi api = SupabaseConfig.getRetrofit().create(SupabaseApi.class);
api.login(SupabaseConfig.SUPABASE_KEY, credentials).enqueue(new Callback<SupabaseResponse>() {
@Override
public void onResponse(Call<SupabaseResponse> call, Response<SupabaseResponse> response) {
if (response.isSuccessful() && response.body() != null) {
// Guardar o token e o email para usar nas Definições
String token = response.body().access_token;
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("access_token", token);
editor.putString("email", email);
editor.apply();
Toast.makeText(LoginActivity.this, "Entraste com sucesso! 🚀", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(LoginActivity.this, "Dados errados! Verifica a tua password e email.", Toast.LENGTH_LONG).show();
Log.e("SUPABASE", "Erro Login: " + response.code());
}
}
@Override
public void onFailure(Call<SupabaseResponse> call, Throwable t) {
Toast.makeText(LoginActivity.this, "Falha na ligação! Verifica a internet.", Toast.LENGTH_LONG).show();
}
});
});
}
}