Reputation: 96
I am trying to request data from a URL dependant on the lat/lng searched for. this is my method so far but I am having problems with building the URL with the search params;
double latitude = extras.getDouble("latitude");
double longitude = extras.getDouble("longitude");
This is lat lng from prev activity
This is my maps activity method where I will be fetching data I have not made the request yet as I want to get the URL right first
public void getApiData() {
// CMPTODO: build URI
/**
* built a URL with the lat/lng passed from prev activity
*/
String lat = String.valueOf(latitude);
String lng = String.valueOf(longitude);
Uri builtUri = Uri.parse(API_URL).buildUpon()
.appendQueryParameter("lat", lat)
.appendQueryParameter("lng", lng)
.build();
URL urlApi = new URL(builtUri.toString());
//TODO: fetch API data
// TODO: Search prefs adjust lat and long to address in JSON URL.
if (URLUtil.isValidUrl(builtUri)){
}else {
}
}
}
SideNote I am new to Android Dev so I could be going about this the wrong way. any advice is welcomed
URL
public static final String API_URL= "https://data.police.uk/api/crimes-at-location?date=2017-02&lat=52.629729&lng=-1.131592";
Upvotes: 0
Views: 77
Reputation: 8139
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS).build();
final Request.Builder builder = new Request.Builder();
HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
urlBuilder.addEncodedQueryParameter("lat", lat)
urlBuilder.addEncodedQueryParameter("lng", lng)
builder.url(urlBuilder.build().toString());
client.newCall(builder.build())
Upvotes: 0
Reputation: 69709
You need to wrap new URL(builtUri.toString());
inside try - catch
block because new URL(builtUri.toString());
may throw MalformedURLException
MalformedURLException
Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.
Try this
URL urlApi;
try {
urlApi = new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
Upvotes: 1
Reputation: 1720
Follow the following steps
String URL = YOUR_API_URL;
Uri.Builder builder = Uri.parse(URL).buildUpon();
builder.appendQueryParameter("value", your_value);
URL=builder.build().toString();
Upvotes: 1