Required to store the Firebase Response in arraylist - android

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

Related

Displaying data from a Json array using Retrofit in a textview

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());
}
});

How to get response from server as String ,Retrofit 1.9

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

Android Retrofit GET #Query ArrayList

I am trying to consume a GET API that expects in its query params list an array of strings.
I am using Retrofit for the task.
In the API interface, I have the following defined:
#GET("user/explore")
Observable<User> fetchUsers(#Query("who") String who,
#Query("category") ArrayList<String> categories);
I am using Timber for logging and in the console, I see the request is made like the following:
http://192.168.2.208:3000/api/v1/user/explore?who=SOME_USER&category=SOME_CATEGORY
The expected request should be made like the following:
http://192.168.2.208:3000/api/v1/user/explore?who=SOME_USER&category=[SOME_CATEGORY,SOME_CATEGORY1,SOME_CATEGORY2]
Why is retrofit behaving this way event though categories are of type string arraylist?
ArrayList<String> carArrList = new ArrayList<>();
carArrList.add("a");
carArrList.add("b");
carArrList.add("c");
String[] catArr = (String[]) carArrList.toArray(new String[carArrList.size()]);
String catStr = Arrays.toString(catArr);
catStr = catStr.replaceAll(" ", "");
Log.e("catStr", catStr);
Call<User> call = apiService.fetchUsers(catStr);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
}
#Override
public void onFailure(Call<User> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
#GET("list/")
Call<User> fetchUsers(#Query("category") String categories);
final request generated
list/?category=[a,b,c]

How to handle response which can be different Type in Retrofit 2

In WebApi returned JSON's field can be of different class:
{ someField:"some string" }
{ someField: { "en" : "some string", "ka" : "რამე სტრინგი" } }
I've seen some solutions, but it was on previous versions of Retrofit.
How would my pojo class look like and what can i use to parse this dynamic json?
For your case you can use Call<JsonElement> as response type and parse it in response:
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
if(response.isSuccessful()){
JsonElement jsonElement = response.body();
if(jsonElement.isJsonObject()){
JsonObject objectWhichYouNeed = jsonElement.getAsJsonObject();
}
// or you can use jsonElement.getAsJsonArray() method
//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");
}
});

Retrofit 2 Post response to different class

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");
}
});

Categories

Resources