What is wrong with my url (google place api and retrofit) - android

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=45.537284299999996,-73.576391125&radius=1000&types=amusement_park|restaurant|cafe|restaurant|library&rankby=distance&key=apikey
I'm using retrofit. Here is my code:
Retrofit api interface:
ublic interface PlaceApiRequestInterface {
#GET("/maps/api/place/nearbysearch/json")
//synch request: all wait on the same thread
public Response getJson(#Query("location") String location,
#Query("radius") String radius,
#Query("rankby") String rankby,
#Query("types") String types,
#Query("key") String key);
}
Then how I set my values
LatLng locationLatLong = obtenirLeCentre(membres);
String location = locationLatLong.latitude+","+locationLatLong.longitude;
//radius_
String radius = ""+radius_;
//rankby_ is an attribute whose value is "distance"
//type
Set<String> uniqueElements = new HashSet<String>(listPreferences_);
listPreferences_.clear();
listPreferences_.addAll(uniqueElements);
String type = "";
int taille = listPreferences_.size();
for(int i = 0 ; i < taille; i++){
if(i == taille - 1)
type += Converter.converter_.nameToPlaceType(listPreferences_.get(i));
else
type += Converter.converter_.nameToPlaceType(listPreferences_.get(i))+"|";
}
setupClient();
//2- get the answer from my http call
String reponseHttp = Converter.converter_.fromResponseToString(get().getJson(location,radius,rankBy,type,googleKey));
I get this as an answer:
{
"html_attributions" : [],
"results" : [],
"status" : "INVALID_REQUEST"
}
Blockquote
Can one help me to discover what is wrong here?
Thanks.

Related

how to check a key value is string or Integer (ios,Android) both

Hello every one am newly in app development ,I have a json data and there is key (order_id) some time order_id value is return ("order_id": "188") but some time return Integer like that ("order_id": 188) .is there any way to find that is return string or Integer in ios(swift) and android both thanks
here is example of json response
"orders": [
{
"order_id": "188",
"invoice_id": "OR180413-188",
"order_status": "1"
}
]
And some time like that
"orders": [
{
"order_id": 188,
"invoice_id": "OR180413-188",
"order_status": "1"
}
]
Android :
Object order_id = jsonarray.getJsonObject(0).getInt("order_id");
Object invoice_id = jsonarray.getJsonObject(0).getString("invoice_id");
Object order_status= jsonarray.getJsonObject(0).getInt("order_status");
if(order_id instanceOf String)
// do what you want
.....
May be this will help you
Swift
You can use like:
let str = "188" // Your response string or Int here
var sInt:Int = Int()
// Check if 's' is a String
if str is String {
print("Yes, it's a String")
sInt = Int(str)!
print(sInt)
}else{
print("Not a string")
}
Another Way is:
You can forcefully convert it to string and then Int for safer side
let str = "\(strResponse)" // Your String here
let strToInt = Int(str)
You could decode it as string even when it's an integer with Swift 4:
struct Order: Decodable {
private enum CodingKeys: String, CodingKey {
case orderId = "order_id"
}
let orderId: String
init(from decoder: Decoder) throws {
let container = try? decoder.container(keyedBy: CodingKeys.self)
if let orderId = try container?.decodeIfPresent(String.self, forKey: .orderId) {
self.orderId = orderId
} else if let orderId = try container?.decodeIfPresent(Int.self, forKey: .orderId) {
self.orderId = String(orderId)
} else {
throw DecodingError.dataCorrupted(DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Couldn't decode orderId"
))
}
}
}

how to send both string and array type parameter on server in android

I want to send data like packageid[]=1&packageid[]2. The same applies for the amount. The key will be the same, but the value will be different.My Packageid[] would be same and values would be different.and my question is different.
HashMap<String,String> params1 = new HashMap<String,String>();
params1.put("customerId", String.valueOf(helpervalue));
params1.put("vechileId", String.valueOf(vehicalId));
params1.put("timeslotId", String.valueOf(timeSlotId));
params1.put("registrationYear", String.valueOf(registeryear));
params1.put("franchiseId", String.valueOf(helpervalue2));
params1.put("jobDate", String.valueOf(date));
params1.put("vehicleRegistrationNumber", String.valueOf(register));
params1.put("totalAmount", String.valueOf(total)+"&"+getURlFromArray1(strint));`
private String getURlFromArray1(int arr[]) {
String makeupSTR = "";
for(int val : arr)
makeupSTR += arr1Key+"="+val+"&";
if(makeupSTR.contains("&"))
makeupSTR = makeupSTR.substring(0, makeupSTR.lastIndexOf("&"));
return makeupSTR;
}
I am expecting to send the following query string structure:
?access=true&action=place_order&type=Add&franchiseId=1&jobDate=2016-01-30&customerId=1&vehicleRegistrationNumber=1&vehicleMakeId=1&registrationYear=2016&totalAmount=250.36&packageIds[]=1&packageIds[]=2&packageAmounts[]=20&packageAmounts[]=30
which responds with JSON like
{
status: false,
displayMessage: "This Slot has just been booked. Please Select a different Time Slot."
}
You need to decide how to send this "array". You can simply send it as a ;-separated string: key=val1;val2;val3, for example. In server, you split them using ;.
Example:
String values[] = { "1", "2", "3" };
String all = "";
for (String v : values)
all += v + ";";
all = all.substring(0, all.length() - 1);
String param = "key=" + all;
You can better send json/xml.

How to split a string using regex

I'm parsing a json file with this code:
JSONObject stationJson = array.optJSONObject(i);
Station s = new Station();
s.setName(stationJson.optString("name"));
s.setTimestamp(stationJson.optString("last_update"));
s.setNumber(stationJson.optInt("number"));
This is the json file :
{
"number": 123,
"contract_name" : "7500 - London",
"name": "nom station",
"address": "adresse indicative",
}
I would like to display just the "London" in the name section not the Number.
I found this Code Snippet but I don't know how to use it :
case spots:
number = pSpotsJSON.optString("id");
name = pSpotsJSON.optString("name");
address = pSpotsJSON.optString("description");
status = pSpotsJSON.optString("status");
displayName = buildDisplayName(name);
break;
default:
throw new IllegalArgumentException("Cannot parse spots from JSON: unknown provider " + provider.getName());
}
}
private String buildDisplayName(String name) {
String regexp = "[\\d\\s]*([a-zA-Z](.*)$)";
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(name);
if (m.find()) {
return m.group();
}
return name;
}
Any help would be great!
What about getting a substring after the "-" of your String?
Would give something like this:
String contractName = stationJson.getString("contract_name");
contractName = contractName.substring(contractName.indexOf("-")+2); //+2 for the minus + space caracters

Accessing Json object information

I am developing an android app, in that i have to make a call to my remote server,it will give me data in terms of json object. in following format.
{
-source: {
LS: " ABCDEF",
name: "XYXA",
point: "77.583859,12.928751"
},
-stores: [
-{
ph: null,
distance: "0.3",
LS: " abcd",
id: 1209,
name: "xyz",
point: "77.583835,12.926359"
},
-{
ph: null,
distance: "0.3",
LS: " abcd",
id: 1209,
name: "xyz",
point: "77.583835,12.926359"
}
]
}
i have confirmed that server is giving me response. But i'm not getting how to access this data in my application.
Can anybody give me a code to access these data.?
Thanking you
JSONObject jsonObject=new JSONObject(responseString);
String LS=jsonObject.getJSONObject("source").get("LS").toString();
String name=jsonObject.getJSONObject("source").get("name").toString();
String point=jsonObject.getJSONObject("source").get("point").toString();
String[] latlng = point.split(",");
String lat=latlng[0];
String lng=latlng[1];
System.out.println("Lat "+lat+" Lng "+lng);
JSONArray jsonArray=jsonObject.getJSONArray("stores");
if (jsonArray.length()>0)
{
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String ph=jsonObject1.get("ph").toString();
String distance=jsonObject1.get("distance").toString();
String LS=jsonObject1.get("LS").toString();
String id=jsonObject1.get("id").toString();
String name=jsonObject1.get("name").toString();
String point=jsonObject1.get("point").toString();
String[] latlng = point.split(",");
String lat=latlng[0];
String lng=latlng[1];
System.out.println("Lat "+lat+" Lng "+lng);
}
}
Here is the complete parsing code section.
Try to parse your JSON response as below:
JSONArray arra = new JSONArray("stores");
for(int i=0;i<arra.length();i++)
{
JSONObject json = arra.getJSONObject(i);
//Retrieve the data from the JSON object
String name= json.getString("name");
String points = json.getString("point");
String loc=json.getString("LS");
}
EDITED:
Extract the lat,long from string point you need to use the StringTokenizer to split the string as below:
StringTokenizer stoken = new StringTokenizer(points, ",");
while (stoken.hasMoreTokens()) {
System.err.println(stoken.nextToken());
}

json android: parsing json

I have a json :
[ {user:"John",s:"Ldh",e:"usa"},{user:"Paul",s:"bukit panjang ",e:"FedExForum - Memphis"},{user:"ross",s:"bukit panjang ",e:"FedExForum - Memphis "}]
I am parsing this with the following code to retrieve all the values of "user" ..
public class ListViewAndroidActivity extends ListActivity {
private String newString, user;
ArrayList<String> results = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TestServiceActivity test = new TestServiceActivity(); //This returns json from the server
newString = test.readPooledFeed(); // returned json in string format
JSONArray rootArray = new JSONArray(newString);
int len = rootArray.length();
for(int i = 0; i < len; ++i) {
JSONObject obj = rootArray.getJSONObject(i);
user = obj.optString("user");
results.add(user);
}
}
This gives me no error.. but nothing is shown on the screen .. kindly help!
optString : Get an optional string associated with a key.
I don't see the key u in your JSON object, shouldn't it be user = obj.optString("user");
JSON formatting
Your JSON data is not valid, it's valid as javascript, but not as JSON.
All properties should be quoted in JSON:
[
{ "user": "John", "s": "Ldh", "e": "usa"},
{ "user":"Paul", "s":"bukit panjang ", "e": "FedExForum - Memphis" },
{ "user": "ross", "s":"bukit panjang ", "e":"FedExForum - Memphis "}
]
Indentation is not needed, I just did it to make it clearer.
Missing field
Your parser seems to ignore that your input data is invalid. Other problem could be as others mentioned you're requesting the u property at user = obj.optString("u"); which does not exists.

Categories

Resources