When I try to register or login a user using a database (php) in android studio I get the following error in the logcat: java.lang.illegalstateesception expected begin_object but was string (Android Studio). Also, in the logcat I can observe the following problems:
E/SystemUpdater-DataParser: [AppList] JSON : list is null No value for miuiApp. E/SystemUpdater-DataParser: [AppList] JSON : list is null. No value for listApp E/adTracker: Value [email protected] of type java.lang.String cannot be converted to JSONObject E/adTracker: Value [email protected] of type java.lang.String cannot be converted to JSONObject E/adTracker: Value [email protected] of type java.lang.String cannot be converted to JSONObject
This is my code: Constants class (in the url base I have my ip, the problem is not this parameter).
public class Constants {
public static final String BASE_URL = "http://10.0.2.2/";
public static final String REGISTER_OPERATION = "register";
public static final String LOGIN_OPERATION = "login";
public static final String CHANGE_PASSWORD_OPERATION = "chgPass";
public static final String SUCCESS = "success";
public static final String FAILURE = "failure";
public static final String IS_LOGGED_IN = "isLoggedIn";
public static final String NAME = "name";
public static final String EMAIL = "email";
public static final String UNIQUE_ID = "unique_id";
public static final String TAG = "C4Growth";
}
Login Fragment:
package nutriapp.nut.nut.activities;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import nutriapp.nut.nut.Constants;
import nutriapp.nut.nut.R;
import nutriapp.nut.nut.model.RequestInterface;
import nutriapp.nut.nut.model.User;
import nutriapp.nut.nut.model.ServerResquest;
import nutriapp.nut.nut.model.ServerResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class LoginFragment extends Fragment implements View.OnClickListener{
private AppCompatButton btn_login;
private EditText et_email,et_password;
private TextView tv_register;
private ProgressBar progress;
private SharedPreferences pref;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login,container,false);
initViews(view);
return view;
}
private void initViews(View view){
pref = getActivity().getPreferences(0);
btn_login = (AppCompatButton)view.findViewById(R.id.btn_login);
tv_register = (TextView)view.findViewById(R.id.tv_register);
et_email = (EditText)view.findViewById(R.id.et_email);
et_password = (EditText)view.findViewById(R.id.et_password);
progress = (ProgressBar)view.findViewById(R.id.progress);
btn_login.setOnClickListener(this);
tv_register.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_register:
goToRegister();
break;
case R.id.btn_login:
String email = et_email.getText().toString();
String password = et_password.getText().toString();
if(!email.isEmpty() && !password.isEmpty()) {
progress.setVisibility(View.VISIBLE);
loginProcess(email,password);
} else {
Snackbar.make(getView(), "Fields are empty !", Snackbar.LENGTH_LONG).show();
}
break;
}
}
private void loginProcess(String email,String password){
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
User user = new User();
user.setEmail(email);
user.setContra(password);
ServerResquest request = new ServerResquest();
request.setOperation(Constants.LOGIN_OPERATION);
request.setUser(user);
Call<ServerResponse> response = requestInterface.operation(request);
response.enqueue(new Callback<ServerResponse>() {
@Override
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
ServerResponse resp = response.body();
Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();
if(resp.getResult().equals(Constants.SUCCESS)){
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(Constants.IS_LOGGED_IN,true);
editor.putString(Constants.EMAIL,resp.getUser().getEmail());
editor.putString(Constants.NAME,resp.getUser().getName());
editor.putString(Constants.NAME,resp.getUser().getId());
editor.putString(Constants.UNIQUE_ID,resp.getUser().getId());
editor.apply();
}
progress.setVisibility(View.INVISIBLE);
}
@Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
progress.setVisibility(View.INVISIBLE);
Log.d(Constants.TAG,"failed");
Snackbar.make(getView(), t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
private void goToRegister(){
Fragment register = new RegisterFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame,register);
ft.commit();
}
}
Register fragment:
public class RegisterFragment extends Fragment implements View.OnClickListener{
private AppCompatButton btn_register;
private EditText et_email,et_password,et_name,et_altura,et_weight,et_age;
private TextView tv_login;
private ProgressBar progress;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_register,container,false);
initViews(view);
return view;
}
private void initViews(View view){
btn_register = (AppCompatButton)view.findViewById(R.id.btn_register);
tv_login = (TextView)view.findViewById(R.id.tv_login);
et_name = (EditText)view.findViewById(R.id.et_name);
et_email = (EditText)view.findViewById(R.id.et_email);
et_password = (EditText)view.findViewById(R.id.et_password);
et_weight = (EditText)view.findViewById(R.id.et_weight);
et_altura = (EditText) view.findViewById(R.id.et_altura);
et_age = (EditText) view.findViewById(R.id.et_age);
progress = (ProgressBar)view.findViewById(R.id.progress);
btn_register.setOnClickListener(this);
tv_login.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_login:
goToLogin();
break;
case R.id.btn_register:
String name = et_name.getText().toString();
String email = et_email.getText().toString();
String password = et_password.getText().toString();
String altura = et_altura.getText().toString();
String weight = et_weight.getText().toString();
String age = et_age.getText().toString();
if(!name.isEmpty() && !email.isEmpty() && !password.isEmpty() && !altura.isEmpty() && !weight.isEmpty()) {
progress.setVisibility(View.VISIBLE);
registerProcess(name,email,password,altura,weight,age);
} else {
Snackbar.make(getView(), "Fields are empty !", Snackbar.LENGTH_LONG).show();
}
break;
}
}
private void registerProcess(String name, String email,String password,String altura, String weight, String age){
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
User user = new User();
user.setName(name);
user.setEmail(email);
user.setContra(password);
user.setAlt(altura);
user.setWeight(weight);
user.setOld(age);
ServerResquest request = new ServerResquest();
request.setOperation(Constants.REGISTER_OPERATION);
request.setUser(user);
Call<ServerResponse> response = requestInterface.operation(request);
response.enqueue(new Callback<ServerResponse>() {
@Override
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
ServerResponse resp = response.body();
Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();
progress.setVisibility(View.INVISIBLE);
}
@Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
progress.setVisibility(View.INVISIBLE);
Log.d(Constants.TAG,"failed");
Snackbar.make(getView(), t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
private void goToLogin(){
Fragment login = new LoginFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame,login);
ft.commit();
}
}
User class:
public class User {
@SerializedName("unique_id")
private String unique_id;
@SerializedName("name")
private String name;
@SerializedName("email")
private String email;
@SerializedName("old")
private String old;
@SerializedName("weight")
private String weight;
@SerializedName("alt")
private String alt;
@SerializedName("password")
private String password;
public String getId(){
return unique_id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getOld(){
return old;
}
public void setOld(String old){
this.old = old;
}
public String getWeight(){
return weight;
}
public void setWeight(String weight){
this.weight=weight;
}
public String getAlt(){
return alt;
}
public void setAlt(String alt){
this.alt = alt;
}
public String getContra(){
return contra;
}
public void setContra(String contra){
this.contra = contra;
}
}
ServerRequest class:
import com.google.gson.annotations.SerializedName;
public class ServerResquest {
@SerializedName("operation")
private String operation;
@SerializedName("user")
private User user;
public void setOperation(String operation) {
this.operation = operation;
}
public void setUser(User user) {
this.user = user;
}
}
Retrofit class:
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl){
if(retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Class Request interface
public interface RequestInterface {
@POST("login/")
Call<ServerResponse> operation(@Body ServerResquest request);
}
Php codes:
db-connect:
include_once 'config.php';
class DbConnect{
private $connect;
public function __construct(){
$this->connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($this->connect)){
echo "Fallo al conectar a la base de datos de MySQL: " . mysqli_connect_error();
}
}
public function getDb(){
return $this->connect;
}
}
?>
user.php:
include_once 'db-connect.php';
class User{
private $db;
private $db_table = "t_user";
public function __construct(){
$this->db = new DbConnect();
}
public function isLoginExist($email, $password){
$query = "select * from ".$this->db_table." where email = '$email' AND password = '$password' Limit 1";
$result = mysqli_query($this->db->getDb(), $query);
if(mysqli_num_rows($result) > 0){
mysqli_close($this->db->getDb());
return true;
}
mysqli_close($this->db->getDb());
return false;
}
public function isEmailUsernameExist($username, $email){
$query = "select * from ".$this->db_table." where name = '$name' AND email = '$email'";
$result = mysqli_query($this->db->getDb(), $query);
if(mysqli_num_rows($result) > 0){
mysqli_close($this->db->getDb());
return true;
}
return false;
}
public function isValidEmail($email){
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
public function createNewRegisterUser($name, $email, $tipo, $alt, $weight, $password){
$isExisting = $this->isEmailUsernameExist($username, $email);
if($isExisting){
$json['success'] = 0;
$json['message'] = "Error al registrar. Es posible que el usuario/correo ya exista.";
}
else{
$isValid = $this->isValidEmail($email);
if($isValid)
{
$query = "insert into ".$this->db_table." (name, email, tipo, alt, weight, PASSWORD) values ('$name', '$email', '$tipo, $alt, $weight, '$password')";
$inserted = mysqli_query($this->db->getDb(), $query);
if($inserted == 1){
$json['success'] = 1;
$json['message'] = "Usuario registrado correctamente.";
}else{
$json['success'] = 0;
$json['message'] = "Error al registrar. Es posible que el usuario/correo ya exista.";
}
mysqli_close($this->db->getDb());
}
else{
$json['success'] = 0;
$json['message'] = "Error al registrar. Dirección de correo no válida.";
}
}
return $json;
}
public function loginUsers($username, $password){
$json = array();
$canUserLogin = $this->isLoginExist($username, $password);
if($canUserLogin){
$json['success'] = 1;
$json['message'] = "Successfully logged in";
}else{
$json['success'] = 0;
$json['message'] = "Incorrect details";
}
return $json;
}
}
?>
index.php:
require_once 'user.php';
$name = "";
$password = "";
$email = "";
$tipo = "";
$alt = "";
$weight = "";
if(isset($_POST['name'])){
$username = $_POST['username'];
}
if(isset($_POST['password'])){
$password = $_POST['password'];
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}
if(isset($_POST['tipo'])){
$email = $_POST['tipo'];
}
I have another php called config in which I have the name of the database, the password of this, the user and the host.