How to post a JSON array using retrofit 2? - java

How to post JSON array using retrofit2 in Android?
here i attatch format of data
{
"lat": 11.024,
"lon": 75.054,
"maxdistance": 5000,
"amintyArray": [
"5ad251cfe601aa22a8f48d98",
"5ad251dae601aa22a8f48d99",
"5ad251ece601aa22a8f48d9a"
],
"starArray": [
"5ad252b1e601aa22a8f48db1"
]
}

pojo class like blow..
public class Example {
#SerializedName("lat")
#Expose
private Double lat;
#SerializedName("lon")
#Expose
private Double lon;
#SerializedName("maxdistance")
#Expose
private Integer maxdistance;
#SerializedName("amintyArray")
#Expose
private List<String> amintyArray = null;
#SerializedName("starArray")
#Expose
private List<String> starArray = null;
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public Integer getMaxdistance() {
return maxdistance;
}
public void setMaxdistance(Integer maxdistance) {
this.maxdistance = maxdistance;
}
public List<String> getAmintyArray() {
return amintyArray;
}
public void setAmintyArray(List<String> amintyArray) {
this.amintyArray = amintyArray;
}
public List<String> getStarArray() {
return starArray;
}
public void setStarArray(List<String> starArray) {
this.starArray = starArray;
}
}

make request pojo class like below it define array or single value..
public class JsonData {
#SerializedName("createdAt")
private long createdAt;
#SerializedName("firstName")
private String firstName;
#SerializedName("password")
private String password;
#SerializedName("users")
private List<User> users;
public long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(long createdAt) {
this.createdAt = createdAt;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
after that make api for requesting ..
#POST("linke")
Call<Response> passJsonData(#Body JsonData jsonData);
after insert data into Json data object then pass only json data.

Related

Retrofit Body isn't showing desired response from Nested JSON

I've been trying to connect an Android App to the Fitbit API using Retrofit however I'm struggling with getting a connection to a JSON with a nested user section. I've managed to get the classes set up however get Body: com.example.myapplication.User#6fe68c1 when requesting the body back.
Whilst learning about Retrofit I've had no problems with using however this seems to be different because of the "user" in the JSON.
Shortened JSON I'm working from
{
"user": {
"age": 23,
"avatar": "https://static0.fitbit.com/images/profile/defaultProfile_100.png",
"averageDailySteps": 2673,
"dateOfBirth": "1999-01-25",
"displayName": "Name.",
"features": {
"exerciseGoal": true
},
"fullName": "Full Name",
"gender": "MALE",
"glucoseUnit": "METRIC",
"height": 180.3,
"memberSince": "2022-02-28",
"startDayOfWeek": "MONDAY",
"strideLengthRunning": 123.10000000000001,
"weight": 72.5,
}
}
Fitbit Class
imports
#Generated("jsonschema2pojo")
public class Fitbit {
#SerializedName("user")
#Expose
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
User Class
imports
#Generated("jsonschema2pojo")
public class User {
#SerializedName("age")
#Expose
private Integer age;
#SerializedName("avatar")
#Expose
private String avatar;
#SerializedName("averageDailySteps")
#Expose
private Integer averageDailySteps;
#SerializedName("dateOfBirth")
#Expose
private String dateOfBirth;
#SerializedName("fullName")
#Expose
private String fullName;
#SerializedName("gender")
#Expose
private String gender;
#SerializedName("height")
#Expose
private Double height;
#SerializedName("memberSince")
#Expose
private String memberSince;
#SerializedName("startDayOfWeek")
#Expose
private String startDayOfWeek;
#SerializedName("strideLengthRunning")
#Expose
private Double strideLengthRunning;
#SerializedName("strideLengthWalking")
#Expose
private Double strideLengthWalking;
#SerializedName("timezone")
#Expose
private String timezone;
#SerializedName("waterUnitName")
#Expose
private String waterUnitName;
#SerializedName("weight")
#Expose
private Double weight;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public Integer getAverageDailySteps() {
return averageDailySteps;
}
public void setAverageDailySteps(Integer averageDailySteps) {
this.averageDailySteps = averageDailySteps;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
public String getMemberSince() {
return memberSince;
}
public void setMemberSince(String memberSince) {
this.memberSince = memberSince;
}
public String getStartDayOfWeek() {
return startDayOfWeek;
}
public void setStartDayOfWeek(String startDayOfWeek) {
this.startDayOfWeek = startDayOfWeek;
}
public Double getStrideLengthRunning() {
return strideLengthRunning;
}
public void setStrideLengthRunning(Double strideLengthRunning) {
this.strideLengthRunning = strideLengthRunning;
}
public Double getStrideLengthWalking() {
return strideLengthWalking;
}
public void setStrideLengthWalking(Double strideLengthWalking) {
this.strideLengthWalking = strideLengthWalking;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public String getWaterUnitName() {
return waterUnitName;
}
public void setWaterUnitName(String waterUnitName) {
this.waterUnitName = waterUnitName;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
}
JsonPlaceholderAPI Interface Class
imports
public interface JsonPlaceholderAPI {
#Headers({"Authorization: Bearer bearercodeinserted"})
#GET("https://api.fitbit.com/1/user/-/profile.json")
Call<User> getUser();
}
MainActivity
public class MainActivity extends AppCompatActivity {
private TextView textViewResult;
private JsonPlaceholderAPI jsonPlaceholderAPI;
#Override
protected void onCreate(Bundle savedInstanceState) {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewResult = findViewById(R.id.text_view_result);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
jsonPlaceholderAPI = retrofit.create(JsonPlaceholderAPI.class);
getUser();
}
private void getUser() {
Call<User> call = jsonPlaceholderAPI.getUser();
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
if (!response.isSuccessful()) {
textViewResult.setText("Code: " + response.code());
return;
}
textViewResult.setText("Body: " + response.body());
}
#Override
public void onFailure(Call<User> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
}
}
Solution:
Change Call<User>() to Call<Fitbit>()
and response.body().getUser().toString()
If you want textViewResult.setText("Body: " + response.body()); to give you string representation of your User data you have to override toString() function on your User object. For example:
public class User {
#SerializedName("age")
#Expose
...
#Override
String toString() {
return "age: " + age + " avatar: " + avatar + ....;
}
}

How to Fetch data from API using Retrofit in Android

I'm Trying to call API using retrofit in Android. Although I'm successfully able to api in response I'm getting Success Code = 200. But Apart from that Inside Json object Json array is null although while I'm trying to call same api in Postman I'm getting the desire result.
I'm trying to call using POST request
URL Request :- https://example.com/AD1/api/user/profile
I'm passing parameter in Body userid:- MFL176116
Below Postman
APIInterface.java
public interface APIInterface {
#POST("profile")
Call<ProfilePojo> getUserProfile(#Body ProfilePojo profilePojo);
}
ProfilePojo.java
public class ProfilePojo {
#SerializedName("message")
#Expose
private String message;
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("user_data")
#Expose
private List<UserDatum> userData = new ArrayList();
private String userid;
public ProfilePojo(String userid) {
this.userid = userid;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<UserDatum> getUserData() {
return userData;
}
public void setUserData(List<UserDatum> userData) {
this.userData = userData;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public class UserDatum {
#SerializedName("id")
#Expose
private String id;
#SerializedName("username")
#Expose
private String username;
#SerializedName("password")
#Expose
private String password;
#SerializedName("under_id")
#Expose
private String underId;
#SerializedName("place_under_id")
#Expose
private String placeUnderId;
#SerializedName("mobile")
#Expose
private String mobile;
#SerializedName("side")
#Expose
private String side;
#SerializedName("email")
#Expose
private String email;
#SerializedName("status")
#Expose
private String status;
#SerializedName("member_name")
#Expose
private String memberName;
#SerializedName("package_id")
#Expose
private String packageId;
#SerializedName("package_id1")
#Expose
private String packageId1;
#SerializedName("avatar")
#Expose
private String avatar;
#SerializedName("gender")
#Expose
private Object gender;
#SerializedName("date_of_birth")
#Expose
private Object dateOfBirth;
#SerializedName("address_line1")
#Expose
private String addressLine1;
#SerializedName("address_line2")
#Expose
private String addressLine2;
#SerializedName("country")
#Expose
private String country;
#SerializedName("country_code")
#Expose
private String countryCode;
#SerializedName("state")
#Expose
private String state;
#SerializedName("city")
#Expose
private String city;
#SerializedName("pincode")
#Expose
private String pincode;
#SerializedName("pancard_no")
#Expose
private String pancardNo;
#SerializedName("adharcard_no")
#Expose
private String adharcardNo;
#SerializedName("franchaise_type")
#Expose
private String franchaiseType;
#SerializedName("franchise_id")
#Expose
private Object franchiseId;
#SerializedName("franchise_per")
#Expose
private Object franchisePer;
#SerializedName("franchise_status")
#Expose
private Object franchiseStatus;
#SerializedName("transaction_pass")
#Expose
private String transactionPass;
#SerializedName("id_proof")
#Expose
private Object idProof;
#SerializedName("address_proof")
#Expose
private Object addressProof;
#SerializedName("self_video")
#Expose
private String selfVideo;
#SerializedName("residential_proof")
#Expose
private String residentialProof;
#SerializedName("btc_address")
#Expose
private Object btcAddress;
#SerializedName("perfect_money")
#Expose
private Object perfectMoney;
#SerializedName("email_status")
#Expose
private String emailStatus;
#SerializedName("email_verify")
#Expose
private String emailVerify;
#SerializedName("created_on")
#Expose
private String createdOn;
#SerializedName("edited_on")
#Expose
private String editedOn;
#SerializedName("isDeleted")
#Expose
private String isDeleted;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUnderId() {
return underId;
}
public void setUnderId(String underId) {
this.underId = underId;
}
public String getPlaceUnderId() {
return placeUnderId;
}
public void setPlaceUnderId(String placeUnderId) {
this.placeUnderId = placeUnderId;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getSide() {
return side;
}
public void setSide(String side) {
this.side = side;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public String getPackageId() {
return packageId;
}
public void setPackageId(String packageId) {
this.packageId = packageId;
}
public String getPackageId1() {
return packageId1;
}
public void setPackageId1(String packageId1) {
this.packageId1 = packageId1;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public Object getGender() {
return gender;
}
public void setGender(Object gender) {
this.gender = gender;
}
public Object getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Object dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getPancardNo() {
return pancardNo;
}
public void setPancardNo(String pancardNo) {
this.pancardNo = pancardNo;
}
public String getAdharcardNo() {
return adharcardNo;
}
public void setAdharcardNo(String adharcardNo) {
this.adharcardNo = adharcardNo;
}
public String getFranchaiseType() {
return franchaiseType;
}
public void setFranchaiseType(String franchaiseType) {
this.franchaiseType = franchaiseType;
}
public Object getFranchiseId() {
return franchiseId;
}
public void setFranchiseId(Object franchiseId) {
this.franchiseId = franchiseId;
}
public Object getFranchisePer() {
return franchisePer;
}
public void setFranchisePer(Object franchisePer) {
this.franchisePer = franchisePer;
}
public Object getFranchiseStatus() {
return franchiseStatus;
}
public void setFranchiseStatus(Object franchiseStatus) {
this.franchiseStatus = franchiseStatus;
}
public String getTransactionPass() {
return transactionPass;
}
public void setTransactionPass(String transactionPass) {
this.transactionPass = transactionPass;
}
public Object getIdProof() {
return idProof;
}
public void setIdProof(Object idProof) {
this.idProof = idProof;
}
public Object getAddressProof() {
return addressProof;
}
public void setAddressProof(Object addressProof) {
this.addressProof = addressProof;
}
public String getSelfVideo() {
return selfVideo;
}
public void setSelfVideo(String selfVideo) {
this.selfVideo = selfVideo;
}
public String getResidentialProof() {
return residentialProof;
}
public void setResidentialProof(String residentialProof) {
this.residentialProof = residentialProof;
}
public Object getBtcAddress() {
return btcAddress;
}
public void setBtcAddress(Object btcAddress) {
this.btcAddress = btcAddress;
}
public Object getPerfectMoney() {
return perfectMoney;
}
public void setPerfectMoney(Object perfectMoney) {
this.perfectMoney = perfectMoney;
}
public String getEmailStatus() {
return emailStatus;
}
public void setEmailStatus(String emailStatus) {
this.emailStatus = emailStatus;
}
public String getEmailVerify() {
return emailVerify;
}
public void setEmailVerify(String emailVerify) {
this.emailVerify = emailVerify;
}
public String getCreatedOn() {
return createdOn;
}
public void setCreatedOn(String createdOn) {
this.createdOn = createdOn;
}
public String getEditedOn() {
return editedOn;
}
public void setEditedOn(String editedOn) {
this.editedOn = editedOn;
}
public String getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(String isDeleted) {
this.isDeleted = isDeleted;
}
}
}
Dashboard.java
private void getUserProfile() {
apiInterface = ApiLinks.getClient().create(APIInterface.class);
ProfilePojo profilePojo = new ProfilePojo("MFL176116");
Call<ProfilePojo> call = apiInterface.getUserProfile(profilePojo);
call.enqueue(new Callback<ProfilePojo>() {
#Override
public void onResponse(#NonNull Call<ProfilePojo> call, #NonNull Response<ProfilePojo> response) {
ProfilePojo profilePojo = response.body();
Toast.makeText(getApplicationContext(), "sucess", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(#NonNull Call<ProfilePojo> call, #NonNull Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
After debugging the code can see Message is success, code =200, but userdata size ==0 please help me to get rid of this error
Check again the way that you are calling the api, even your userid is getting null, probably it's getting null in the user, but the response is 200 bc there was no error, simply no user with that id.

Only one HTTP method is allowed. Found GET and PUT

java.lang.IllegalArgumentException: Only one HTTP method is allowed. Found: GET and PUT.
for method ApiInterface.UpdateCoordinates
i have tried for the last 2 hours to update the coordinates but it ain't working keeps throwing this error
java.lang.IllegalArgumentException: Only one HTTP method is allowed. Found: GET and PUT.
for method ApiInterface.UpdateCoordinates
at retrofit2.Utils.methodError(Utils.java:52)
at retrofit2.Utils.methodError(Utils.java:42)
at retrofit2.RequestFactory$Builder.parseHttpMethodAndPath(RequestFactory.java:251)
at retrofit2.RequestFactory$Builder.parseMethodAnnotation(RequestFactory.java:224)
at retrofit2.RequestFactory$Builder.build(RequestFactory.java:171)
at retrofit2.RequestFactory.parseAnnotations(RequestFactory.java:67)
at retrofit2.ServiceMethod.parseAnnotations(ServiceMethod.java:26)
at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:170)
at retrofit2.Retrofit$1.invoke(Retrofit.java:149)
at java.lang.reflect.Proxy.invoke(Proxy.java:1006)
at $Proxy0.UpdateCoordinates(Unknown Source)
at com.example.charlo.jkuat_mobile_app.util.LocationService$1.onLocationResult(LocationService.java:54)
Model classes
the update model class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class GpsUpdate {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("data")
#Expose
private Data data;
#SerializedName("message")
#Expose
private String message;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
model class
the data model class
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Data {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("driverid")
#Expose
private Integer driverid;
#SerializedName("companyid")
#Expose
private Integer companyid;
#SerializedName("vehicleid")
#Expose
private Integer vehicleid;
#SerializedName("warehouseid")
#Expose
private Integer warehouseid;
#SerializedName("orders")
#Expose
private Integer orders;
#SerializedName("status")
#Expose
private Integer status;
#SerializedName("latitute")
#Expose
private String latitute;
#SerializedName("longitude")
#Expose
private String longitude;
#SerializedName("tripdate")
#Expose
private String tripdate;
#SerializedName("created_at")
#Expose
private String createdAt;
#SerializedName("updated_at")
#Expose
private String updatedAt;
public Data(String latitute, String longitude) {
this.latitute = latitute;
this.longitude = longitude;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getDriverid() {
return driverid;
}
public void setDriverid(Integer driverid) {
this.driverid = driverid;
}
public Integer getCompanyid() {
return companyid;
}
public void setCompanyid(Integer companyid) {
this.companyid = companyid;
}
public Integer getVehicleid() {
return vehicleid;
}
public void setVehicleid(Integer vehicleid) {
this.vehicleid = vehicleid;
}
public Integer getWarehouseid() {
return warehouseid;
}
public void setWarehouseid(Integer warehouseid) {
this.warehouseid = warehouseid;
}
public Integer getOrders() {
return orders;
}
public void setOrders(Integer orders) {
this.orders = orders;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getLatitute() {
return latitute;
}
public void setLatitute(String latitute) {
this.latitute = latitute;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getTripdate() {
return tripdate;
}
public void setTripdate(String tripdate) {
this.tripdate = tripdate;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
}
Interface
interface class
#PUT("update_driver/{dispatchid}?")
Call<GpsUpdate> UpdateCoordinates(#Path("dispatchid") int id, #Field("latitude") String latitude, #Field("longitude") String longitude );
location service class
the update class which sends the coordinates to the backend
#Override
public void onCreate() {
super.onCreate();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
tokenManager = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
service = ApiClient.createService(ApiInterface.class);
locationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
double lat = locationResult.getLastLocation().getLatitude();
double lng = locationResult.getLastLocation().getLongitude();
String latitude = String.valueOf(lat);
String longitude = String.valueOf(lng);
Data data = new Data(latitude,longitude);
Call<GpsUpdate> call = service.UpdateCoordinates(tokenManager.getToken().getDispatchid(),data.getLatitute(), data.getLongitude());
call.enqueue(new Callback<GpsUpdate>() {
#Override
public void onResponse(Call<GpsUpdate> call, Response<GpsUpdate> response) {
}
#Override
public void onFailure(Call<GpsUpdate> call, Throwable t) {
}
});
I think I should have marked this as a duplicate:
Retrofit: how fix "only one http method is allowed. found: get and get"?
Try changing the
#Path("dispatchid") int id
to
#Path("dispatchid") int dispatchid

Failed to convert value of type java.lang.Double to String

I have tried many solutions this code worked for me in the morning and again when i am running it now it is showing an unknown error here is my user class
and I have even tried converting it into doubl also didnt work anyone please help me.
public class createuser {
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 getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getIssharing() {
return issharing;
}
public void setIssharing(String issharing) {
this.issharing = issharing;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public createuser() {
}
public String name, email, password, code, issharing, lat, lng,
imgurl, userid;
public createuser(String name, String email, String password, String
code, String issharing, String lat, String lng, String imgurl, String
userid) {
this.name = name;
this.email = email;
this.password = password;
this.code = code;
this.issharing = issharing;
this.lat = lat;
this.lng = lng;
this.imgurl = imgurl;
this.userid = userid;
}
}
here is my runtime class
code = (EditText)findViewById(R.id.editText);
submit = (Button)findViewById(R.id.button);
firebaseDatabase = FirebaseDatabase.getInstance();
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
reference =
firebaseDatabase.getInstance().getReference().child("users");
currentreference =
firebaseDatabase.getInstance().getReference().child("users")
.child(user.getUid());
current_user_id = user.getUid();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
query =
reference.orderByChild("code").equalTo(code.getText().toString());
query.addListenerForSingleValueEvent
(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot
dataSnapshot) {
if (dataSnapshot.exists())
{
createuser createuser = null;
for (DataSnapshot childDss :
dataSnapshot.getChildren())
{
createuser =
childDss.getValue(createuser.class);
join_user_id = createuser.userid;
circlereference =
firebaseDatabase.getInstance().getReference().child("users")
.child(join_user_id).child("Circlemembers");
circlejoin circlejoin = new
circlejoin(current_user_id);
circlejoin circlejoin1 = new
circlejoin(join_user_id);
circlereference.child(user.getUid()).setValue(circlejoin)
.addOnCompleteListener(new
OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull
Task<Void> task) {
if (task.isSuccessful())
{
Toast.makeText(getApplicationContext(),"user joined
circle",Toast.LENGTH_SHORT).show();
startActivity(new
Intent(joincircle.this,userlocation.class));
}
}
});
}
}
else
{
Toast.makeText(getApplicationContext(),"circle
code is invalid",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError
databaseError) {
}
});
}
});
}
Realtime database is like this
users
NwKzgM0NhuY7gT7eFiN9nwzumMG2
code: "7260232"
email: "trackit385#gmail.com"
imgurl: "na"
issharing: "false"
lat: 17.3932339
lng: 78.4440638
name: "tejesh"
password: "kinglion"
userid: "NwKzgM0NhuY7gT7eFiN9nwzumMG2"
anyone please help me i am not able to resolve it my error is
com.google.firebase.database.DatabaseException: Failed to convert
value of type java.lang.Double to String
You get the following error:
com.google.firebase.database.DatabaseException: Failed to convert
value of type java.lang.Double to String
Because your lat and lng fields in your createuser class are of type String while in your database both fileds hold a double value and this is not correct. To solve this, simply change the type of your fields in your class to double.
public class createuser {
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 getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getIssharing() {
return issharing;
}
public void setIssharing(String issharing) {
this.issharing = issharing;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public createuser() {
}
public String name, email, password, code, issharing,
imgurl, userid;
public double lat, lng;
public createuser(String name, String email, String password, String
code, String issharing, double lat, double lng, String imgurl, String
userid) {
this.name = name;
this.email = email;
this.password = password;
this.code = code;
this.issharing = issharing;
this.lat = lat;
this.lng = lng;
this.imgurl = imgurl;
this.userid = userid;
}
}
I don't know, but this class lacks all of it's field declarations. That should be Double lat, Double lng. When the field is String and the setter method sets double, this cannot work, at least not unless adding a matching setter. Also Double and double is not the same data-type. You're confusing primitive with complex data-types (on here they also have two different shades of blue) and also defining setters, but not using them in the constructor ...of which second may be a matter of taste, but first is syntactically wrong, because it means: call by value vs. call by reference. The class probably should be simply called User, because you might end up using it throughout the application.
public class User {
private Double lat;
private Double lng;
...
public User() {}
public User(String name, String email, String password, String code, String issharing, Double lat, Double lng, String imgurl, String userid) {
...
}
...
public Double getLat() { return this.lat; }
public Double getLng() { return this.lng; }
public void setLat(Double value) { this.lat = value; }
public void setLng(Double value) { this.lng = value; }
}

ObjectMapper can't map the variables of inner class

ObjectMapper mapper = new ObjectMapper();
try {
attractionMainResponse = mapper.readValue(response,AttractionMainResponse.class);
} catch(IOException io) {
showToast("Something went wrong");
FirebaseCrash.log(io.toString());
finish();
}
AttractionMainResponse :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionMainResponse {
private AttractionDetailModel Attraction_Info;
private String response;
public AttractionMainResponse() {
Attraction_Info = null;
response =null;
}
public AttractionMainResponse(AttractionDetailModel aa,String ab) {
Attraction_Info = aa;
response = ab;
}
public AttractionDetailModel getAttraction_Info() {
return Attraction_Info;
}
public void setAttraction_Info(AttractionDetailModel attraction_Info) {
Attraction_Info = attraction_Info;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
AttractionDetailModel :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AttractionDetailModel {
private AddressDataAttraction address_data;
private List<Image> Images;
private TypesInAttraction Type;
private String architect;
private String architectural_style;
private int city_id;
private String founder;
private String description;
private int id;
private String name;
private String height;
private String opened_since;
private String popularity;
private String timings;
private String visitors;
private String profile_image_url;
public AttractionDetailModel() {
address_data = null;
architect = null;
architectural_style = null;
city_id=-1;
founder = null;
description = null;
id=-1;
name=null;
height=null;
opened_since=null;
popularity = null;
timings=null;
visitors=null;
Images = null;
Type=null;
profile_image_url=null;
}
public AttractionDetailModel(AddressDataAttraction address_data, List<Image> images, TypesInAttraction type, String architect, String architectural_style, int city_id, String founder, String description, int id, String name, String height, String opened_since, String popularity, String timings, String visitors, String profile_image_url) {
this.address_data = address_data;
Images = images;
Type = type;
this.architect = architect;
this.architectural_style = architectural_style;
this.city_id = city_id;
this.founder = founder;
this.description = description;
this.id = id;
this.name = name;
this.height = height;
this.opened_since = opened_since;
this.popularity = popularity;
this.timings = timings;
this.visitors = visitors;
this.profile_image_url = profile_image_url;
}
public String getProfile_image_url() {
return profile_image_url;
}
public void setProfile_image_url(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public AddressDataAttraction getAddress_data() {
return address_data;
}
public void setAddress_data(AddressDataAttraction address_data) {
this.address_data = address_data;
}
public List<Image> getImages() {
return Images;
}
public void setImages(List<Image> images) {
Images = images;
}
public TypesInAttraction getType() {
return Type;
}
public void setType(TypesInAttraction type) {
Type = type;
}
public String getArchitect() {
return architect;
}
public void setArchitect(String architect) {
this.architect = architect;
}
public String getArchitectural_style() {
return architectural_style;
}
public void setArchitectural_style(String architectural_style) {
this.architectural_style = architectural_style;
}
public int getCity_id() {
return city_id;
}
public void setCity_id(int city_id) {
this.city_id = city_id;
}
public String getFounder() {
return founder;
}
public void setFounder(String founder) {
this.founder = founder;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getOpened_since() {
return opened_since;
}
public void setOpened_since(String opened_since) {
this.opened_since = opened_since;
}
public String getPopularity() {
return popularity;
}
public void setPopularity(String popularity) {
this.popularity = popularity;
}
public String getTimings() {
return timings;
}
public void setTimings(String timings) {
this.timings = timings;
}
public String getVisitors() {
return visitors;
}
public void setVisitors(String visitors) {
this.visitors = visitors;
}
}
AddressDataAttractions :
#JsonIgnoreProperties (ignoreUnknown = true)
public class AddressDataAttraction {
private String address;
private String city;
private String country;
private String landmark;
private float latitude;
private float longitude;
private String pincode;
private String state;
public AddressDataAttraction() {
address=null;
city=null;
country=null;
landmark=null;
latitude=-1;
longitude=-1;
pincode=null;
state=null;
}
public AddressDataAttraction(String address, String city, String country, String landmark, float latitude, float longitude, String pincode, String state) {
this.address = address;
this.city = city;
this.country = country;
this.landmark = landmark;
this.latitude = latitude;
this.longitude = longitude;
this.pincode = pincode;
this.state = state;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLandmark() {
return landmark;
}
public void setLandmark(String landmark) {
this.landmark = landmark;
}
public float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
TypeInAttraction :
#JsonIgnoreProperties (ignoreUnknown = true)
public class TypesInAttraction{
private String type;
private int id ;
public TypesInAttraction() {
type=null;
id=-1;
}
public TypesInAttraction(String type, int id) {
this.type = type;
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
In debug mode, string response in objectMapper shows correct response, string response in attractionMainResponse giving a success but can't map the attractionDetailModel, giving null.
Is this about a Jackson ObjectMapper? Is it possible to create a smaller example, that makes it easier to give a solution.

Categories

Resources