Android mapping does not work - android

Hi I have to send map to server and the server will get information from that. I'm having two piece of code for mapping first is(name and key are variables)
String user = "{ 'id':" + userId +","+"'response':{'id':"+userId+",'access':"+"'"+name+":"+key+"'"+"}}";
Map<String, Object> userMap = new Gson().fromJson(user, new TypeToken<HashMap<String, Object>>() {}.getType());
Set<String> keys = userMap.keySet();
for (String i:keys){
Log.d("user",i+" "+userMap.get(i));
}
here I concat required string and parse it and then convert it into map . This piece of code had worked. And my second set of code is
String user1 = "{id="+userId+", access="+""+name+":"+key+""+"}";
Map<String,Object> tuc = new HashMap<>();
tuc.put("id",userId);
tuc.put("access","");
Set<String> key = tuc.keySet();
for (String i:key){
Log.d("user",i+" "+tuc.get(i));
}
this code is not working,that mean server is not accepting this code. But when I print key value pairs the results are same for both codes. My lead doesn't like to use first piece of code. Can any one explain why,I'm struck in this for past two days. Thank you.Sorry for my poor English.

In Java, HashMap can only accept <key, value> pairs. It is not like Json, which in your case is in {key1:value1, key2:value2, ...} format.
Therefore, if you are intended to convert its format from {key1:value1, key2:value2, ...} into <key, value>. My suggestion is combining value2, value3, ... into an object (like String) as the value and value1 as the key.
See https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html for more details.

Related

Retrofit - Send request body as array or number

I'm using Retrofit 2 and I need to send request body. The problem is somehow the value is converted to string. On the example below, you can see that items and totalPrice which should be array and number respectively are converted to string.
{ cashierId: 'fff7079c-3fc2-453e-99eb-287521feee63',
items: '[{"amount":3,"id":"602a79e3-b4c1-4161-a082-92202f92d1d6","name":"Play Station Portable","price":1500000.0}]',
paymentMethod: 'Debt',
totalPrice: '4500000.0' }
The desired request body is
{ cashierId: 'fff7079c-3fc2-453e-99eb-287521feee63',
items: [{"amount":3,"id":"602a79e3-b4c1-4161-a082-92202f92d1d6","name":"Play Station Portable","price":1500000.0}],
paymentMethod: 'Debt',
totalPrice: 4500000.0 }
Here's the service
#POST("api/sales")
#FormUrlEncoded
Call<Sale> createSale(
#FieldMap Map<String, Object> fields
);
And this is how I call createSale
Map<String, Object> fields = new HashMap<>();
fields.put("cashierId", UUID.fromString("fff7079c-3fc2-453e-99eb-287521feeaaa"));
fields.put("totalPrice", totalPrice);
fields.put("paymentMethod", paymentMethod);
fields.put("items", jsonArray);
Call<Sale> call = retailService.createSale(fields);
Is it possible to send those values as number and array, not as string?
The conversion most certainly happens because you are using #FormUrlEncoded.
According to the documentation:
Field names and values will be UTF-8 encoded before being URI-encoded in accordance to RFC-3986.
A solution would be to use a model class instead of a Map. I see you already have a Sale class. If it looks like something like this:
public class Sale {
String cashierId;
int totalPrice;
String paymentMethod;
ArrayList<SomeObject> items;
}
you can simply do like this:
// in service
#POST("api/sales")
Call<Sale> createSale(#Body Sale sale);
// when doing the call
Sale sale = new Sale();
// set everything in your object
// then
Call<Sale> call = retailService.createSale(sale);

How send an array or list of strings in retrofit with same key but different indexes?

I have an api that accepts multiple values with same key but different index e.g.
phone_no[0]="1234"
phone_no[1]="5678"
I need to send an array or list of strings that contains phone numbers. I have tried using
#FormUrlEncoded
#POST("get_user_by_phone.php")
Call<PojoGetFriendsListResponse> getUserFromPhone(#Field("phone_no") ArrayList<String> phone_no);
but it generates request body like below
phone_no=%2B1234&phone_no=%2B5678
is there any way to generate a requestbody like this?
phone_no[0]=%2B1234&phone_no[1]=%2B5678
Try This:
HashMap<String, String> phoneNumbers= new HashMap<>();
phoneNumbers.put("phone_no[0]", "99912443432");
phoneNumbers.put("phone_no[1]", "99912443433");
phoneNumbers.put("phone_no[2]", "99912443434");
#FormUrlEncoded
#POST("get_user_by_phone.php")
Call<PojoGetFriendsListResponse> getUserFromPhone(#FieldMap HashMap<String, String> phoneNumbers);

Storing JSON data to local database in android

Okay so, I created an app that retrieves data from my server using JSON. Now I want to store the retrieved data on my phone's local storage/db. How do I do it? I am new in android programming.
This is the JSON that I receive from the server
{"messages":[{"id":"44","issender":0,"content":"CAT1DOG","date":"Jan 01, 1970 07:30 AM","sender":"Administrator","receiver":"User"},{"id":"57","issender":0,"content":"ttt","date":"Jun 30, 2016 03:43 PM","sender":"Administrator","receiver":"User"},{"id":"58","issender":0,"content":"s","date":"Jun 30, 2016 03:43 PM","sender":"Administrator","receiver":"User"},{"id":"82","issender":0,"content":"yeuwu","date":"Jun 30, 2016 04:59 PM","sender":"Administrator","receiver":"User"}],"success":1}
and this is my code to parse JSON
for(int i = 0; i < messages.length(); i++){
JSONObject o = messages.getJSONObject(i);
String msgid = o.getString("id");
String message = o.getString("content");
String date = o.getString("date");
String sender = o.getString("sender");
String receiver = o.getString("receiver");
String issender = o.getString("issender");
// TEMP HASHMAP FOR USER
HashMap<String, String> msgList = new HashMap<String, String>();
// ADDING EACH CHILD NOTE TO HASHMAP => VALUE
msgList.put("id", uid);
msgList.put("message", message);
msgList.put("date", date);
msgList.put("name", sender);
msgList.put("receivername", receiver);
// ADDING USER TO MSGLIST
ListOfMsg.add(msgList);
}
Thanks in advance for those who will answers. will appreciate it.
First I need to tell you that this is not the easy way out but for sure it is the correct one.
Next create a new class named Message
public class Message{
public String issender;
}
When you receive the json :
List<Message> messages= new ArrayList<>();
Gson gson = new Gson();
Message m= gson.fromJson(json.toString(),Message.class);
messages.add(m);
Please be careful that the items in the class should have the name as the items in the json you are trying to receive
Now we are done with this part:
Let us add the library for caching:
Follow this tutorial and if you need help get back to me:
https://guides.codepath.com/android/activeandroid-guide
or you could do the caching using sql old fashioned way
You can do this in two ways:
Use the new extension for json in sqite. The information you might need is available on this page https://www.sqlite.org/json1.html . Still I would suggest to do a little bit more of research on this, as it is new and I have not used it yet.
You can convert your json to string and insert it to the database.
String jsontostring = jsonObject.toString();

Pass multiple values to single parameter retrofit2

I'm trying to pass multiple Values to a SINGLE parameter for example :
http://api.giphy.com/v1/gifs?api_key=dc6zaTOxFJmzC&ids=feqkVgjJpYtjy,7rzbxdu0ZEXLy
I tried the following :
#GET("gifs")
Call<GIFModelMain> getGifsByID(#Field("ids")ArrayList<String> values, #Query("api_key") String API_KEY);
In my activity :
ArrayList<String> x = new ArrayList<>();
x.add("feqkVgjJpYtjy");
x.add("7rzbxdu0ZEXLy");
gifCall = interf.getGifsByID(x, BuildConfig.GIPHY_API_TOKEN);
But the built URL is of form:
http://api.giphy.com/v1/gifsids=feqkVgjJpYtjy&ids=7rzbxdu0ZEXLy&api_key=API_KEY_BLANK
I looked up similar questions but found no correct answer.
EDIT: As per what TooManyEduardos said i changed my Interface to
#GET("gifs")
Call<GIFModelMain> getGifsByID(#QueryMap Map<String, String> parameters,#Query("api_key") String API_KEY);
And my activity is now :
Map<String,String> map = new HashMap<>();
map.put("ids","feqkVgjJpYtjy");
map.put("ids","7rzbxdu0ZEXLy");
gifCall = interf.getGifsByID(map, BuildConfig.GIPHY_API_TOKEN);
But the built URL is still :
03-30 02:46:23.922: E/FavActivity(21607): Url : api.giphy.com/v1/gifs?ids=7rzbxdu0ZEXLy&api_key=KEY_HERE
You're looking for a
Map<String,String>
And in your #Get interface, you'll receive it like this:
(#QueryMap Map<String, String> parameters)
So your whole interface call would be like this:
#GET("gifs")
Call<GIFModelMain> getGifsByID(#QueryMap Map<String, String> parameters);
I wrote a whole tutorial on how to use Retrofit 2 if you want to check it out: http://toomanytutorials.blogspot.com/2016/03/network-calls-using-retrofit-20.html
EDIT
If you really want to pass multiple parameters, regardless of their key name, you can always do this:
Call<GIFModelMain> getGifsByID(#Query("api_key") String API_KEY, #Query("ids") String id1, #Query("ids") String id2, #Query("ids") String id3);
The obvious problem here is that you'll have to make multiple versions of the same method depending on how many ids you're passing

Android - Is it possible to have a lookup array?

I know there's an answer to this, but i'm not sure what to search and cannot remember the right phrasing.
Essentially what i mean, i'm being passed an integer. I want to search through an array using this integer to return a string value.
E.g.
I'm given the number 2. My lookup array looks like so:
array.add(1, "Auckland")
array.add(2, "Wellington")
array.add(3, "Bay of Plenty")
When i iterate through the array, i want to return "Wellington".
Can someone point me in the right direction please? :)
Hi you should declare a HashMap of Integer String:
HashMap<Integer, String> map= new HashMap<Integer, String>();
map.put(1, "Auckland");
map.put(2, "Wellington");
map.put(3, "Bay of Plenty");
And then to get the String you should call the HashMap using the key:
String yourString = map.get(1);

Categories

Resources