Solution 1 :
Your model is not representing same data as in JSON. With UserOrtu
class it will works only if your response will have structure like below:
{
"id":1,
"nama": "Name",
"email":"email",
"message":"msg"
}
But as you can see 3 first fields are inside another object data
. So your model should look more like:
class LoginResponse{
@SerializedName("data")
@Expose
private UserOrtu userData;
@SerializedName("message")
@Expose
private String message;
}
Problem :
I want to make a fitur to login, I want to make a feature to log in, initially I saw the response code shows 200, but when I saw the response body was null. I can still log in, but the logged in user data isn’t saved. I used 2 db MySql and SQLite and im using retrofit and shared preference. And here my code
API Interface
public interface Api {
@FormUrlEncoded
@POST(Config.API_LOGIN_USER)
Call<UserOrtu> loginUser(
@Field("email") String email,
@Field("password") String password
);
PrefUtil.java
public class PrefUtil {
public static final String USER_SESSION = "user_session";
public static final String USER_STORAGE = "user_storage";
public static SharedPreferences getSharedPreferences(Context ctx){
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void putUser(Context ctx, String key, UserOrtu user){
Gson gson = new Gson();
String json = gson.toJson(user);
putString(ctx, key, json);
}
public static UserOrtu getUser(Context ctx, String key){
Gson gson = new Gson();
String json = getString(ctx, key);
UserOrtu user = gson.fromJson(json, UserOrtu.class);
return user;
}
public static void putString(Context ctx, String key, String value){
getSharedPreferences(ctx).edit().putString(key, value).apply();
}
public static String getString(Context ctx, String key){
return getSharedPreferences(ctx).getString(key, null);
}
public static void clear(Context ctx) {
getSharedPreferences(ctx).edit().clear().apply();
}
}
Models
UserOrtu.java
public class UserOrtu {
@SerializedName("id_user")
@Expose
private int idUser;
@SerializedName("nama")
@Expose
private String nama;
@SerializedName("email")
@Expose
private String email;
@SerializedName("password")
@Expose
private String password;
@SerializedName("error")
@Expose
private Boolean error;
@SerializedName("message")
@Expose
private String message;
public int getIdUser() {
return idUser;
}
public void setIdUser(int idUser) {
this.idUser = idUser;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Boolean getError() {
return error;
}
public void setError(Boolean error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
SignInActivity.java
public class SignInActivity extends AppCompatActivity {
@BindView(R.id.input_email_signin)
TextInputEditText etEmail;
@BindView(R.id.text_register)
TextView tvRegister;
@BindView(R.id.input_password_signin)
TextInputEditText etPassword;
EmailValidator emailValidator;
PasswordValidator passwordValidator;
Context context;
private String email;
private String password;
private Api mApi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (isSessionLogin()){
startActivity(new Intent(this, MainActivity.class));
this.finish();
}
setContentView(R.layout.activity_sign_in);
ButterKnife.bind(this);
AndroidThreeTen.init(this);
mApi = RetrofitBuilder.builder(this).create(Api.class);
}
boolean isEmail(EditText text){
emailValidator = new EmailValidator();
String email = text.getText().toString();
return emailValidator.isValid(email);
}
boolean isPassword(EditText text){
passwordValidator = new PasswordValidator();
String pass = text.getText().toString();
return passwordValidator.isValid(pass);
}
@OnClick(R.id.text_register) void toRegister(){
Intent intent = new Intent(this, SignUpActivity.class);
startActivity (intent);
}
@OnClick(R.id.btn_signin) void onLogin(){
if(isEempty(etEmail)){
etEmail.setError("Email harus diisi");
}else if(isEempty(etPassword)){
etPassword.setError("Password harus diisi");
}else if(!isEmail(etEmail)){
etEmail.setError("Email tidak valid");
}else if(!isPassword(etPassword)){
String str = passwordValidator.getString();
Toast.makeText(getApplicationContext(),str, Toast.LENGTH_SHORT).show();
}else {
loginAct();
}
}
void loginAct(){
email = etEmail.getText().toString();
password = etPassword.getText().toString();
final MaterialDialog dialog = DialogBuilder.showLoadingDialog(SignInActivity.this, "Updating Data", "Please wait..", false);
mApi.loginUser(email, password).enqueue(new Callback<UserOrtu>() {
@Override
public void onResponse(Call<UserOrtu> call, Response<UserOrtu> response) {
UserOrtu user = response.body();
Log.i("USER_LOGIN", response.message());
if (user != null){
//Masih error disini
//if (!user.getError()){
PrefUtil.putUser(getApplicationContext(), PrefUtil.USER_SESSION, user);
Intent intent = new Intent(SignInActivity.this, MainActivity.class);
startActivity(intent);
//this.finish();
//}
Toast.makeText(getApplicationContext(), user.getMessage(), Toast.LENGTH_SHORT).show();
}
if (response.code() == 403){
etPassword.requestFocus();
etPassword.setError(getString(R.string.error_password));
}
if (response.code() == 404){
etEmail.requestFocus();
etEmail.setError(getString(R.string.error_login));
}
dialog.dismiss();
}
@Override
public void onFailure(Call<UserOrtu> call, Throwable t) {
//Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
dialog.dismiss();
Log.i("USER_LOGIN", t.getMessage());
DialogBuilder.showErrorDialog(SignInActivity.this, "Gagal Login");
}
});
}
// this method to check is user logged in ?
boolean isSessionLogin(){
return PrefUtil.getUser(getApplicationContext(), PrefUtil.USER_SESSION) != null;
}
}
And here’s my result
enter image description here
Here’s my JSON request
enter image description here
Comments
Comment posted by Alpha 1
I can’t find any issue in your reponse, body is not nul. In the screenshot, you can see the message = “Berhasil” right? Code is working fine. Please check your API, what it returns.
Comment posted by Tiramochi
yes, the message is succes a.k.a “Berhasil” . But, user data in the form of id, name, e-mail does not appear and the value is null
Comment posted by github.com/square/okhttp/tree/master/okhttp-logging-interceptor
Are you sure that your class
Comment posted by Tiramochi
for the JSON request, I’ve added it to my question. Thank you, I will try it