Am using retrofit and RxJava to Connect to API. Data is being successfully posted to Server but i would like to get the Token which the API generates after posting data.
This is for Authentication of user using a JSON Web Token Django Backend
The models are working fine but Here are my Models:
public class User {
#SerializedName("user")
#Expose
private User_ user;
public User_ getUser() {
return user;
}
public void setUser(User_ user) {
this.user = user;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("user", user).toString();
}
}
public class User_ {
#SerializedName("email")
#Expose
private String email;
#SerializedName("password")
#Expose
private String password;
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;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("email", email).append("password", password).toString();
}
}
#SerializedName("user")
#Expose
private LoginResponse_ user;
public LoginResponse_ getUser() {
return user;
}
public void setUser(LoginResponse_ user) {
this.user = user;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("user", user).toString();
}
}
public class LoginResponse_ {
#SerializedName("email")
#Expose
private String email;
#SerializedName("token")
#Expose
private String token;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
#Override
public String toString() {
return new ToStringBuilder(this).append("email", email).append("token", token).toString();
}
}
Retrofit Interface
#POST("auth/login")
#Headers("X-Requested-With:XMLHttpRequest")
Observable<User> login(
#Header("Content-Type") String content_type,
#Body User user
);
}
Retrofit Adapter
public class ServiceGenerator {
private static Retrofit retrofit;
private static Gson gson;
public static synchronized Retrofit getUser() {
if (retrofit == null) {
if (gson == null) {
gson = new GsonBuilder().setLenient().create();
}
retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
Retrofit Instance
public class NetworkUtils {
private static UserService userService;
public static UserService ApiInstance(){
if (userService == null){
userService = ServiceGenerator.getUser().create(UserService.class);
}
return userService;
}
}
This is how am trying to login the user
private void loginProcess(String email, String password) {
User user = new User();
User_ user_ = new User_();
user_.setEmail(email);
user_.setPassword(password);
user.setUser(user_);
mUserService.login("application/json", user)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<User>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(User user) {
showResponse(user.toString());
Log.i(TAG, "Response: "+ user);
mProgressBar.setVisibility(View.GONE);
handleResponse();
}
#Override
public void onError(Throwable e) {
e.printStackTrace();
}
#Override
public void onComplete() {
}
});
}
private void handleResponse(LoginResponse response) {
SharedPreferences.Editor editor = mSharedPreference.edit();
editor.putString(Constants.TOKEN,response.getUser().getToken());
editor.putString(Constants.EMAIL,response.getUser().getEmail());
editor.apply();
mEditTextEmail.setText(null);
mEditTextPassword.setText(null);
Intent intent = new Intent(getActivity(),ProfileActivity.class);
startActivity(intent);
}
It would be really helpful if i get to know how to get response after posting the data to the API.
Using postman this is what i post
{"user":{"email":"user#email.com", "password":"userpassword"}}
And this is the response I get
{
"user": {
"email": "user#email.com",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NSwiZXhwIjoxNTY5MjI5NTgxfQ.S-1yZWNhx_TV8uay8PubGoq9XMpyTIn_ipG8A6DWTfE"
}
}
Related
I have an app that is to register people into a platform but I get a response of Unauthenticated each time I submit the form data. The form is submitted using an API which requires a bearer token for each post request with the aid of retrofit. I have been out of touch with Java.
Note: its just a plain form. No authentication has been implemented in the app.
My ApiClient.java class
public class ApiClient {
private static Retrofit getRetrofit(){
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("xxxxxxxxxxxxx")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
return retrofit;
}
public static UserService getUserService(){
UserService userService = getRetrofit().create(UserService.class);
return userService;
}
}
My UserService.java class
public interface UserService {
#POST("algonapi/api/enroll_vehicle")
Call<UserResponse> saveUser(#Body UserRequest userRequest);
}
My saveUser Method
public void saveUser(UserRequest userRequest){
Call<UserResponse> userResponseCall = ApiClient.getUserService().saveUser(userRequest);
userResponseCall.enqueue(new Callback<UserResponse>() {
#Override
public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
if (response.isSuccessful()){
Toast.makeText(MainActivity.this, "Registration Successfull! Click on Reset Form to Start a New Enumeration...", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(MainActivity.this, "Registration Failed!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<UserResponse> call, Throwable t) {
Toast.makeText(MainActivity.this, "Registration Failed!" +t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
My UserRequest
package com.example.xxxxx;
public class UserRequest {
private String FullName;
private String StickerNumber;
private String Address;
private String Email;
private String Phone;
private String Nationality;
private String State;
private String LGA;
private String RC;
private String DriversLicenseNo;
private String LicenseIssued;
private String LicenseExpiry;
private String VehicleType;
private String VehicleLicense;
private String VehicleTyres;
private String LGAofOperation;
private String NOKFullName;
private String NOKAddress;
private String NOKPhone;
private String NOKEmail;
private String NOKNationality;
private String NOKState;
public String getFullName() {
return FullName;
}
public void setFullName(String fullName) {
FullName = fullName;
}
public String getStickerNumber() {
return StickerNumber;
}
public void setStickerNumber(String stickerNumber) {
StickerNumber = stickerNumber;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getNationality() {
return Nationality;
}
public void setNationality(String nationality) {
Nationality = nationality;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
public String getLGA() {
return LGA;
}
public void setLGA(String LGA) {
this.LGA = LGA;
}
public String getRC() {
return RC;
}
public void setRC(String RC) {
this.RC = RC;
}
public String getDriversLicenseNo() {
return DriversLicenseNo;
}
public void setDriversLicenseNo(String driversLicenseNo) {
DriversLicenseNo = driversLicenseNo;
}
public String getLicenseIssued() {
return LicenseIssued;
}
public void setLicenseIssued(String licenseIssued) {
LicenseIssued = licenseIssued;
}
public String getLicenseExpiry() {
return LicenseExpiry;
}
public void setLicenseExpiry(String licenseExpiry) {
LicenseExpiry = licenseExpiry;
}
public String getVehicleType() {
return VehicleType;
}
public void setVehicleType(String vehicleType) {
VehicleType = vehicleType;
}
public String getVehicleLicense() {
return VehicleLicense;
}
public void setVehicleLicense(String vehicleLicense) {
VehicleLicense = vehicleLicense;
}
public String getVehicleTyres() {
return VehicleTyres;
}
public void setVehicleTyres(String vehicleTyres) {
VehicleTyres = vehicleTyres;
}
public String getLGAofOperation() {
return LGAofOperation;
}
public void setLGAofOperation(String LGAofOperation) {
this.LGAofOperation = LGAofOperation;
}
public String getNOKFullName() {
return NOKFullName;
}
public void setNOKFullName(String NOKFullName) {
this.NOKFullName = NOKFullName;
}
public String getNOKAddress() {
return NOKAddress;
}
public void setNOKAddress(String NOKAddress) {
this.NOKAddress = NOKAddress;
}
public String getNOKPhone() {
return NOKPhone;
}
public void setNOKPhone(String NOKPhone) {
this.NOKPhone = NOKPhone;
}
public String getNOKEmail() {
return NOKEmail;
}
public void setNOKEmail(String NOKEmail) {
this.NOKEmail = NOKEmail;
}
public String getNOKNationality() {
return NOKNationality;
}
public void setNOKNationality(String NOKNationality) {
this.NOKNationality = NOKNationality;
}
public String getNOKState() {
return NOKState;
}
public void setNOKState(String NOKState) {
this.NOKState = NOKState;
}
}
Create the OkHttpClient like this
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
#NotNull
#Override
public Response intercept(#NotNull Chain chain) throws IOException {
Request request=chain.request().newBuilder()
.addHeader("Authorization", "Bearer " + token)
.build();
return chain.proceed(request);
}
}).build();
If you most of your https requests need authentication then the first answer is perfect but if some of your requests need then you can pass the header to each methods.
public interface UserService {
#POST("algonapi/api/enroll_vehicle")
Call<UserResponse> saveUser(
#Header("Authorization") String token,
#Body UserRequest userRequest
);
}
While calling the method simply pass your token along with userRequest.
I am trying to login user in my app for that I am using retrofit2 for networking But when after entering email and password my app is crashing and showing below logcat error.
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
Below is my code:
Login response is
{
"data": [
{
"email": "digi#gmail.com",
"address": "Hsbdbshbd"
}
],
"status": true,
"code": 200
}
RetrofitClient.java
public class RetrofitClient {
public static Retrofit retrofit = null;
public static Retrofit getInstance(){
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(22, TimeUnit.SECONDS)
.readTimeout(22, TimeUnit.SECONDS)
.writeTimeout(22, TimeUnit.SECONDS)
.build();
if(retrofit == null)
retrofit = new Retrofit.Builder()
.baseUrl("http://www.gurgaonhomeo.in/api_server/")
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build();
return retrofit;
}
}
ApiService.java
#POST("login")
#FormUrlEncoded
Observable<LoginResponse> loginUser(#Field("email") String email,
#Field("password") String password);
LoginResponse.java
public class LoginResponse {
#Expose
#SerializedName("code")
private String code;
#Expose
#SerializedName("data")
private List<LoginRes> data;
#Expose
#SerializedName("status")
private String status;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public List<LoginRes> getData() {
return data;
}
public void setData(List<LoginRes> data) {
this.data = data;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
LoginRes.java
public class LoginRes {
#SerializedName("address")
private String address;
#SerializedName("email")
private String email;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Login.java
private void signIn(String mail, String pwd) {
Retrofit retrofit = RetrofitClient.getInstance();
ApiService apiService = retrofit.create(ApiService.class);
apiService.loginUser(mail,pwd).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<LoginResponse>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(LoginResponse loginResponse) {
prg.dismiss();
List<LoginRes> res = loginResponse.getData();
Toast.makeText(Login.this, "" +res.get(0).getEmail(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onError(Throwable e) {
TastyToast.makeText(getApplicationContext(),e.getMessage(),TastyToast.LENGTH_LONG,
TastyToast.ERROR).show();
prg.dismiss();
}
#Override
public void onComplete() {
}
});
}
Why am I getting this error?
After List<LoginRes> res = loginResponse.getData(); line check for Log.d("TAG", "response: " +res)
Check if the res value is null or not?
Also check here #POST("login") I think in this part "login", there should be an url of login that will be use after base url.
I want to register a user with their token, I want to register a user using retrofit in android but I keep getting this error:
ERROR::: Attempt to invoke virtual method 'void com.signup.User.setUsername(java.lang.String)' on a null object reference
Here is my code:
public class Session {
Context context;
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
this.context = cntx;
prefs = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setJwtToken(String token) {
prefs.edit().putString("JwtToken", token).commit();
}
public String getJwtToken() {
String token = prefs.getString("JwtToken", "");
if (token == null || token.isEmpty()) {
token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjIxNzc0NTI3OTksImlhdCI6MTUxNjAyMjk5OSwiaXNzIjoiQmFzb2JhYXMgTmVwYWwiLCJuYmYiOjE1MTYwMjI5OTksImp0aSI6Ikd1ZXN0VG9rZW4iLCJzdWIiOjB9.QikmNgBYmqch5HREGFEpUs4Xk3x-zFfDg5mhYJO7jM8";
}
return token;
}
}
public interface ApiInterface {
#POST("/api/users/signup")
Call<ResponseBody> signMeUp(#Header("Authorization") String token ,#Body User user);
}
public class MainActivity extends AppCompatActivity {
private EditText et_name, et_address, et_phone, et_username, et_email, et_password, et_confipassword;
private Button register;
private User user;
private SharedPreferences prefs;
private ApiInterface apiInterface;
private Session session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = findViewById(R.id.edit_text_name);
et_address = findViewById(R.id.edit_text_address);
et_phone = findViewById(R.id.edit_text_phonenumber);
et_username = findViewById(R.id.edit_text_username);
et_email = findViewById(R.id.edit_text_email);
et_password = findViewById(R.id.edit_text_password);
et_confipassword = findViewById(R.id.edit_text_confirm_password);
register = findViewById(R.id.signupButton);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Login();
}
});
}
private void Login() {
user.setUsername(et_name.getText().toString());
user.setAddress(et_address.getText().toString());
user.setPhone(et_phone.getText().toString());
user.setName(et_name.getText().toString());
user.setEmail(et_email.getText().toString());
user.setPassword(et_password.getText().toString());
user.setPasswordConfirmation(et_confipassword.getText().toString());
signupUser(user);
}
private void signupUser(final User user) {
// Set up progressbar before call
apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> call1 = apiInterface.signMeUp(session.getJwtToken(),user);
final Gson gson = new Gson();
final String json = gson.toJson(user);
call1.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.code() == 201) {
try {
JSONObject jsonObject = new JSONObject(response.body().string());
//Starting main activity after user sees dialog
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if (response.code() == 500) {
try {
JSONObject jsonObject = new JSONObject(response.errorBody().string());
Log.e("SignupFragment", jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else
Log.e("SignupFragment", response.raw().toString());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
}
public class User {
#SerializedName("name")
#Expose
private String name;
#SerializedName("email")
#Expose
private String email;
#SerializedName("password")
#Expose
private String password;
#SerializedName("password_confirmation")
#Expose
private String passwordConfirmation;
#SerializedName("image")
#Expose
private String image;
#SerializedName("phone")
#Expose
private String phone;
#SerializedName("address")
#Expose
private String address;
#SerializedName("username")
#Expose
private String username;
#SerializedName("pan_no")
#Expose
private String panNo;
#SerializedName("birthday")
#Expose
private String birthday;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirmation() {
return passwordConfirmation;
}
public void setPasswordConfirmation(String passwordConfirmation) {
this.passwordConfirmation = passwordConfirmation;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPanNo() {
return panNo;
}
public void setPanNo(String panNo) {
this.panNo = panNo;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
public class ApiClient {
public static final String BASE_URL = "https://myapp.herokuapp.com/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
ApiInterface apiInterface=retrofit.create(ApiInterface.class);
}
I want to signup a user via my app but I keep getting the error. And, if I remove the auth from header from my Interface I get a message asking a token, and when I provide a token it give me a null object reference error !!
You should instantiate variable before access it: User user = new User();
Update: do it in void Login()
create an instance of User inside onCreate method or up there where it's declared
Try this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
user = new User();
session = new Session(this);
}
i'm trying to get a JSON from my web service and deserialize to my class UserSync, but i'm getting the following error:
Can not instantiate value of type [simple type, class com.example.breno.teste.model.User] from String value (''); no single-String constructor/factory method
at [Source: okhttp3.ResponseBody$BomAwareReader#fbf814f; line: 1, column: 86] (through reference chain: com.example.breno.teste.dto.UserSync["user"])
I've read some posts saying that i need to declare my User class static in UserSync, but when i do that, jackson can't find any user property, even with JsonDescription. Another posts say that i may need to declare a default constructor, so i did.
Here is the UserSync class:
#JsonIgnoreProperties(ignoreUnknown = true)
public class UserSync {
#JsonProperty("status")
private String Status;
#JsonProperty("currentDate")
private String CurrentDate;
#JsonProperty("message")
private String Message;
#JsonProperty("user")
private static User NewUser;
public UserSync() {
}
public String getStatus() {
return Status;
}
public String getCurrentDate() {
return CurrentDate;
}
public String getMessage() {
return Message;
}
public static User getNewUser() {
return NewUser;
}
The User class:
public class User implements Serializable {
#JsonProperty("userKey")
private UUID UserKey;
#JsonProperty("userPassword")
private String UserPassword;
#JsonProperty("userGroupKey")
private UUID UserGroupKey;
#JsonProperty("signInDate")
private String SignInDate;
#JsonProperty("active")
private boolean Active;
#JsonProperty("profilePicturePath")
private String ProfilePic;
#JsonProperty("completeName")
private String UserCompleteName;
#JsonProperty("email")
private String UserEmail;
#JsonProperty("isLogged")
private boolean IsLogged;
public User() {
}
public boolean getIsLogged() {
return IsLogged;
}
public void setIsLogged(boolean isLogged) {
IsLogged = isLogged;
}
public String getUserEmail() {
return UserEmail;
}
public void setUserEmail(String userEmail) {
UserEmail = userEmail;
}
public UUID getUserKey() {
return UserKey;
}
public void setUserKey(UUID userKey) {
UserKey = userKey;
}
public String getUserPassword() {
return UserPassword;
}
public void setUserPassword(String userPassword) {
UserPassword = userPassword;
}
public UUID getUserGroupKey() {
return UserGroupKey;
}
public void setUserGroupKey(UUID userGroupKey) {
UserGroupKey = userGroupKey;
}
public String getSignInDate() {
return SignInDate;
}
public void setSignInDate(String signInDate) {
SignInDate = signInDate;
}
public boolean getActive() {
return Active;
}
public void setActive(boolean active) {
Active = active;
}
public String getProfilePic() {
return ProfilePic;
}
public void setProfilePic(String profilePic) {
ProfilePic = profilePic;
}
public String getUserCompleteName() {
return UserCompleteName;
}
public void setUserCompleteName(String userCompleteName) {
UserCompleteName = userCompleteName;
}
}
My service class (Using now the postNewUser):
public interface UserService {
#GET("Login/LoginUser?")
Call<UserSync> login(#Query("email") String email, #Query("password") String password);
//region NewUser Services
#GET("Login/VerifyNewUser?")
Call<UserSync> validateNewUser(#Query("email") String email);
#POST("Login/PostNewUser")
Call<UserSync> postNewUser(#Body User user);
//endregion
}
And finally, the JSON:
{
"status": "OK",
"currentDate": "20/07/2017 11:59:02",
"message": "teste",
"user": {
"userKey": "8e2f0d2d-3522-472d-be1d-28791367f4ee",
"email": "teste_teste#hotmail.com",
"userPassword": "123456",
"profilePicturePath": "teste",
"completeName": "Jorge",
"userGroupKey": null,
"signInDate": "2017-07-07T16:26:06.097",
"active": true,
"isLogged": true
}
}
Can someone help me, please?
EDIT 1 - Here is the method that i'm using to do the retrofit call:
public void register(User user) {
Call<UserSync> postCall = new RetrofitInitializator().getUserService().postNewUser(user);
postCall.enqueue(getRegisterCallback());
}
#NonNull
private Callback<UserSync> getRegisterCallback() {
return new Callback<UserSync>() {
#Override
public void onResponse(Call<UserSync> call, Response<UserSync> response) {
User user = response.body().getNewUser();
}
#Override
public void onFailure(Call<UserSync> call, Throwable t) {
Log.e("Register - onFailure", t.getMessage());
}
};
}
EDIT 2 - The retrofitInicializator class:
public class RetrofitInitializator {
private final Retrofit retrofit;
public RetrofitInitializator() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient
.Builder();
builder.addInterceptor(interceptor);
retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.15.6:7071/api/")
.addConverterFactory(JacksonConverterFactory.create())
.client(builder.build())
.build();
}
public UserService getUserService() {
return retrofit.create(UserService.class);
}
}
I managed to resolve my problem switching the type User to JsonNode and doing the convertion after this.
#JsonProperty("status")
private String Status;
#JsonProperty("currentDate")
private String CurrentDate;
#JsonProperty("message")
private String Message;
#JsonProperty("user")
private JsonNode NewUser;
and the convertion:
private User getUserFromUserAsync(UserSync userSync) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.treeToValue(userSync.getNewUser(), User.class);
}
i'm trying to retrieve an inner object from a json response, my json pojo looks like this:
public class Pojo {
private String token;
private User user;
public Pojo()
{}
public Pojo(String username, String password,User user) {
user.setUsername(username);
user.setPassword(password);
this.user = user;
}
public String getToken() {return token;}
public void setToken(String token) {this.token = token;}
public User getUser() {return user;}
public void setUser(User user) {this.user = user;}
and my innerobjct User looks like this:
public class User {
private String username
;
private String name;
private String phone;
private String email;
private String password;
private String is_Active;
}
with their setters and getters
this is my login code:
public void onLogin(View view){
final ProgressDialog dialog = ProgressDialog.show(this, "", "loading...");
EndpointInterface loginService = ServiceAuthGenerator.createService(EndpointInterface.class);
Password = tv_Password.getText().toString();
Username = tv_Username.getText().toString();
User usr = new User();
Pojo user = new Pojo(Username,Password,usr);
Call<Pojo> call = loginService.getToken(usr);
call.enqueue(new Callback<Pojo>() {
#Override
public void onResponse(Response<Pojo> response, Retrofit retrofit) {
dialog.dismiss();
if (response.isSuccess()) {
Pojo user = response.body();
if(user.getUser().getIs_Active()=="True") {
Intent intent = new Intent(getApplicationContext(), MainMenu.class);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(), "Wrong User or Password", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Throwable t) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Error Conection", Toast.LENGTH_SHORT).show();
}
});
}
the response is comming like this:
{
"token":"tokengfsgfds"
"user":{
"username":"exmplename"
"email":"#gomail.com"
"is_active":"True"
}
}
i can retrieve the token, but when i try to get variables from the user inner object my app fails. thanks!
this just mirror code for model classes using Gson library
Pojo.java
import com.google.gson.annotations.SerializedName;
public class Pojo {
#SerializedName("token")
private String token;
#SerializedName("user")
private User user;
public Pojo(String username, String password,User user) {
// TODO Auto-generated constructor stub
user.setUsername(username);
user.setPassword(password);
this.token = "tokengfsgfds";
this.user = user;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
take User out of Pojo and make another class User.java
import com.google.gson.annotations.SerializedName;
public class User {
#SerializedName("username")
private String username;
#SerializedName("name")
private String name;
#SerializedName("phone")
private String phone;
#SerializedName("email")
private String email;
#SerializedName("password")
private String password;
#SerializedName("is_Active")
private boolean is_active;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
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 isIs_active() {
return is_active;
}
public void setIs_active(boolean is_active) {
this.is_active = is_active;
}
}
I used Gson but the output should be the same
import com.google.gson.Gson;
public class TestTwo {
public static void main(String[] args) {
User user = new User();
user.setEmail("someone#gmailcom");
user.setIs_active(true);
user.setName("Cristian");
user.setPassword("Cam");
user.setPhone("1234123441");
user.setUsername("cam.cri");
Pojo pojo = new Pojo("cam.cri", "Cam", user);
String result = (new Gson()).toJson(pojo);
System.out.println(""+result);
Pojo pojo2 = (new Gson()).fromJson(result, Pojo.class);
System.out.println("Token: \t"+pojo2.getToken());
System.out.println("email: \t"+pojo2.getUser().getEmail());
System.out.println("is_active: \t"+pojo2.getUser().isIs_active());
System.out.println("Name: \t"+pojo2.getUser().getName());
System.out.println("Password: \t"+pojo2.getUser().getPassword());
System.out.println("phone: \t"+pojo2.getUser().getPhone());
System.out.println("Username: \t"+pojo2.getUser().getUsername());
}
}
Output
{
"token": "tokengfsgfds",
"user": {
"username": "cam.cri",
"name": "Cristian",
"phone": "1234123441",
"email": "someone#gmailcom",
"password": "Cam",
"is_Active": true
}
}
output
Token: tokengfsgfds
email: someone#gmailcom
is_active: true
Name: Cristian
Password: Cam
phone: 1234123441
Username: cam.cri