Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending multiple dynamic fields with Retrofit

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,

like image 663
Juzmulti Avatar asked Jun 29 '16 08:06

Juzmulti


Video Answer


2 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

like image 194
Sanjay Kakadiya Avatar answered Oct 12 '22 19:10

Sanjay Kakadiya


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.

like image 28
R. Zagórski Avatar answered Oct 12 '22 19:10

R. Zagórski