I'm trying to display data from a Json array using Retrofit on a textfield, however the textfield doesn't show anything. Kindly help.
Here is the request from the retrofit service
#GET("users/:email")
Call<User> getUser(#Query("email") String email );
And how i try to make it display in the text field
Call<User> users = api.getUser(email);
users.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
txtName.setText(response.body().getUserEmail());
}
#Override
public void onFailure(Call<User> call, Throwable t) {
}
});
The response from postman looks like this
[
{
"name": "First Name",
"email": "myemail#gmail.com",
"phone": "00000000"
}
]
First of all you are getting JSON array in response so you need to change your callback accordingly.
change your service call to this
Call<List<User>> getUser(#Query("email") String email );
then
Call<List<User>> users = api.getUser(email);
users.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
List<User> users = response.body();
if(users!=null && users.size()>0)
{
txtName.setText(response.body().get(0).getUserEmail());
}
else
{
txtName.setText("No User found");
}
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
Log.d("USER",t.getMessage());
}
});
Related
I am required to fetch the response mentioned below from firebase by its url. Not by using DatabaseReference or DataSnapshot class. Just by firebase realtime database url.
{
"Emily Aries": "199",
"First Last": "2",
"J J": "194",
"John Deniel": "198",
"Sec User": "3"
}
Here the names and its values are dynamic.This are the values that firebase url returns from specific node named "users". I am required to store names in Names arraylist and ids in ids arraylist.
Here I am attaching the snap of my firebase node structure alongwith code so far I have tried to implement.
ApiInterface.java
#GET("group_chat/Demo Group_2-g/users")
Call<JSONObject> groupUsers();
Snippet from implementation in my main class.
private void getGroupUsersName() {
apiInterface = ApiClient.createService(ApiInterface.class);
Call<JSONObject> call = apiInterface.groupUsers();
call.enqueue(new Callback<JSONObject>() {
#Override
public void onResponse(Call<JSONObject> call, retrofit2.Response<JSONObject> response) {
}
#Override
public void onFailure(Call<JSONObject> call, Throwable t) {
}
});
}
Use
JsonObject
Class from Gson Lib Instead of
JSONObject
#GET("group_chat/Demo Group_2-g/users")
Call<JsonObject> groupUsers();
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
JsonObject jsonObject=response.body();
ArrayList<String> names=new ArrayList<>();
ArrayList<String> ids =new ArrayList<>();
for(Map.Entry<String,JsonElement> entry : jsonObject.entrySet()){
names.add(entry.getKey());
ids.add(jsonObject.get(entry.getKey()).getAsString());
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
}
});
hope it Works
I would like to handle my response from server , but I don't know how JSON (from server) its looks like. So I tried to display response as String , but I cant do it. Is it possible to display response as String? And then handle the response correctly. thanks
(Retrofit 1.9)
LoginService loginService = RetrofitClient.createService(LoginService.class);
loginService.searchOffer(getToken(), offerSearch, new Callback<String>() {
#Override
public void success(String offerSearchRequestResource, Response response) {
String responseFromSercer = response.getBody();
}
#Override
public void failure(RetrofitError error) {
}
});
change your response model to
JSONObject (from Gson)
then in your
public void success(...){response.body.toString();}
like this:
Call<JsonObject> call = YOUR_API_INTERFACE().YOUR_METHOD(YOUR_PARAMS);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, #NonNull Response<JsonObject> response) {
if(response.isSuccessful()) {
String responseFromSercer = response.body.toString();
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
.....
}
});
If you are sure the request runs successfully and there is a response back...use
System.out.println(response.getBody());
i'd also suggest you add Logging Interceptors here so that you can get a detailed view of all your API calls
I am using retrofit:2.1.0 and I am trying to save the response returned to my own POJO (UserProfile) but I can't seem to access the POJO, I assign the response to, outside of the callbacks.
So, in this call below, I want to have access to UserProfile outside of this call.
//adding `UserProfile userProfile;` outside of Call didn't help either
call.enqueue(new Callback<UserProfile>() {
#Override
public void onResponse(Call<UserProfile> call, Response<UserProfile> response) {
if (response.isSuccessful()) {
UserProfile userProfile = response.body();
}
}
#Override
public void onFailure(Call<UserProfile> call, Throwable t) {
//do something
}
});
//here userProfile is null and hence can't get status
Log.d(TAG, "Status outside of Call is: " + userProfile.getStatus());
New approach, same result
private List<UserProfile> userProfileList = new ArrayList<>();
call.enqueue(new Callback<UserProfile>() {
#Override
public void onResponse(Call<UserProfile> call, Response<UserProfile> response) {
if (response.isSuccessful()) {
UserProfile userProfile = response.body();
userProfileList.add(userProfile);
}
}
#Override
public void onFailure(Call<UserProfile> call, Throwable t) {
//do something
}
});
And this one gets fired even before callback and hence is null
if(userProfileList.size() > 0) {
for(UserProfile userProfile : userProfileList) {
Log.d(TAG, "Status is: " + userProfile.getStatus());
}
} else {
Log.d(TAG, "YakkerProfileList is NULL");
}
I added a setter in onResponse() which allowed me to use the response object elsewhere in the code like so:
#Override
public void onResponse(Call<UserProfile> call, Response<UserProfile> response) {
if (response.isSuccessful()) {
UserProfile userProfile = response.body();
//elsewhere in the code, I can read the value from this method
setUserProfile(userProfile.getStatus());
}
}
I want to read response as a custom class but I have to use ResponseBody as a parameter in Post method.
Post interface :
public interface IPostPhoneToken {
#FormUrlEncoded
#POST()
Call<ResponseBody> postPhoneToken(
#Field("data[UserPhoneToken][first_name]") String firstName,
...
#Url String endpoint);
}
Problem is here :
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccessful()){
}
else{
System.out.println(response.message());
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
System.out.println("Failed");
}
});
I want to change ResponseBody with different Class to be able to read response values.
Thanks.
You can use Response<JsonElement> and get as Json object your response and after that use any json deserializer to convert to your class.
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
if(response.isSuccessful()){
JsonElement jsonElement = response.body();
JsonObject objectWhichYouNeed = jsonElement.getAsJsonObject();
//use any json deserializer to convert to your class.
}
else{
System.out.println(response.message());
}
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
System.out.println("Failed");
}
});
I need make POST request with parameters "guid=1" in Body. i use Retrofit2
I try :
#POST("/api/1/model")
Call<ApiModelJson> getPostClub(#Body User body);
User Class:
public class User {
#SerializedName("guid")
String guid;
public User(String guid ) {
this.guid = guid;
}
MailActivity:
User user =new User ("1");
Call<ApiModelJson> call = service.getPostClub(user);
call.enqueue(new Callback<ApiModelJson>() {
#Override
public void onResponse(Response<ApiModelJson> response) {
}
#Override
public void onFailure(Throwable t) {
dialog.dismiss();
}
How make this request?
you have to call call.enqueue, providing an instance of Callback< ApiModelJson>, where you will get the response. enqueue executes your backend call asynchronously. You can read more about call.enqueue here
With code below, you can make the request synchronously:
ApiModelJson responseBody = call.execute();
If you want it to be asynchronous:
call.enqueue(new Callback<ApiModelJson>() {
#Override
public void onResponse(Response<ApiModelJson> response, Retrofit retrofit) {
}
#Override
public void onFailure(Throwable t) {
}
});