Home » Android » android – Sending multiple dynamic fields with Retrofit

android – Sending multiple dynamic fields with Retrofit

Posted by: admin June 16, 2020 Leave a comment

Questions:

We need to send a POST request to a web service that needs dynamic multiple fields.

I mean, we need to send something like this as POST request:

question1='answer1'&question2='answer1'&question2='answer2'&question3='answer1'

where question1 and question2 are not set in compilation time. We know that we can use a @FieldMap for using dynamic fields, but we cannot send the same field more than one time.

This is our Retrofit code:

@FormUrlEncoded
@POST("/desafios/send/")
Observable<BaseServerMsgArray> postSubmitSurvey(@Field("customerId") Long customerId, @Field("upload_from_app") int uploadFromApp, @FieldMap HashMap<String, ArrayList<String>> hashFields);

Could anyone help us?

Thanks in advance,

How to&Answers:

Prepare HashMap like below, put only those questaion that user answered.

 HashMap<String, String> map = new HashMap<>();
 map.put("question1", answer1);
 map.put("question2", answer2);
 map.put("question3", answer3);

change your retrofit as below

@FormUrlEncoded
@POST("/desafios/send/")
Observable<BaseServerMsgArray> postSubmitSurvey(@Field("customerId") Long customerId, @Field("upload_from_app") int uploadFromApp, @FieldMap HashMap<String, String> hashFields);

and pass above HashMap as last argument

Answer:

What you need is a map that can contain duplicate keys. Unfortunately there is no such map in standard Android. You might use this onehttps://github.com/greenrobot/essentials/blob/master/java-essentials/src/main/java/org/greenrobot/essentials/collections/Multimap.java

If this won’t work, try to manually convert your questions to String and send properly formatted String.