How to request in roads api using snap to roads? - java

i would like to use the roads api to get the distance of my currentlocation and add the list of Latlng in onLocationChanged and to snap a set of coordinates (approx 100~200 points) to roads and that will return a json to get the accurate distance of driving.
-- i got a problem with path parameters the latitude and longitude is not populating in which join by this "|" but i got an error like.
---This is my url
protected String getSnapUrl(List<LatLng> pat_value) {
String str_path = null;
for (int x = 0; x < pat_value.size(); x++) {
str_path = "path=" + pat_value.get(x).latitude + "," + pat_value.get(x).longitude + "|";
Log.e("path", "" + pat_value.get(x).latitude + "-" + pat_value.get(x).longitude);
}
String str_interpolate = "interpolate=true";
String key = "key=google key";
String parameters = str_path + "&" + str_interpolate + "&" + key;
String output = "snapToRoads";
String url = output + "?" + parameters;
return url;
}
protected void snapToRoad() {
SnapToRoadAsyncHttpClient.get(getSnapUrl(path), null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("snapToRoad", "" + response);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Log.e("snapToRoadFail", "" + errorResponse + throwable);
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("snapToRoadFail", "" + responseString + throwable);
}
});
}
--Error snaptoroads error:400 message:path.

Status code 400 is due to a invalid request.Roads API takes in at most 100 points , try decreasing your points.

Related

ApolloQueryCall Test in java

I am trying to test onResponse method. If I understand korrectly, when I call apolloQueryCall.enqueue , it should return response as response. When I run this code, it does not enter neither onResponse or onFailere. What am I missing? I could not find examples that work for me on the internet for Java.
String body = "{\n" +
" \"data\": {\n" +
" \"message\": \"kedi\"\n" +
" }\n" +
"}";
MockWebServer webServer = new MockWebServer();
MockResponse response = new MockResponse().setResponseCode(200).setBody(body);
webServer.enqueue(response);
var apolloClient = ApolloClient.builder()
.serverUrl(webServer.url("http://localhost/mock"))
.okHttpClient(okHttpClient)
.build();
var apolloQueryCall = apolloClient.query(query);
apolloQueryCall.enqueue(new ApolloCall.Callback<MyClass.Data>() {
#Override
public void onResponse(#NotNull Response<MyClass.Data> response) {
System.out.println("response:" + response);
}
#Override
public void onFailure(#NotNull ApolloException e) {
System.out.println(e.getMessage());
}
});
webServer.close();

Edit message contents in OneSignal notification Android

I am trying to change the current 'Test Message' String in a OneSignal push notification. I simply want to use a variable defined in my code, but cannot figure out how to do it.
try {
OneSignal.postNotification(new JSONObject("{'contents': ['en': 'Test Message'], 'include_player_ids': ['" + selectedUser.getOneSignalId() + "']}"),
new OneSignal.PostNotificationResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
Log.i("OneSignalExample", "postNotification Success: " + response.toString());
}
#Override
public void onFailure(JSONObject response) {
Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
}
});
} catch (JSONException f) {
e.printStackTrace();
}
I was able to achieve something similar in sending the notification to a selected user. Now I just want to change the text of the actual message.
Use this
String yourVaribale = " what ever you want to send"
OneSignal.postNotification(new JSONObject("{'contents': ['en': " + yourVariable + "], 'include_player_ids': ['" + selectedUser.getOneSignalId() + "']}"),
new OneSignal.PostNotificationResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
Log.i("OneSignalExample", "postNotification Success: " + response.toString());
}
#Override
public void onFailure(JSONObject response) {
Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
}
});
} catch (JSONException f) {
e.printStackTrace();
}
or you can try this way
String strJsonBody = "{"
+ " \"app_id\": \"ef42157d-64e7-4ce2-9ab7-15db224f441b\","
+ " \"included_segments\": [\"All\"],"
+ " \"data\": {\"foo\": \"bar\"},"
+ " \"contents\": {\"en\": \""+ description +"\"},"
+ " \"headings\": {\"en\": \""+ title +"\"},"
+ " \"big_picture\":\""+ imageurl +"\""
+ "}";
for second method follow this link
The solution below worked for me. The full name of the current user is concatenated to the string message " wants you to follow them." and is then sent to the selectedUser with the specific OneSignalID.
OneSignal.postNotification(new JSONObject("{'contents': {'en': \""+ currentUser.getFullName() +" wants you to follow them." +"\"}, 'include_player_ids': ['" + selectedUser.getOneSignalId() + "']}"),
new OneSignal.PostNotificationResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
Log.i("OneSignalExample", "postNotification Success: " + response.toString());
}
#Override
public void onFailure(JSONObject response) {
Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
}
});

Always returning false as boolean value

After user selecting area, there is a function called checkCoverageGuest(). This function checks whether selected area by the user is under coverage for that restaurantor not. If the restaurant is under coverage, then checkCoverageGuest() will return true value. When there is no coverage for that restaurant, checkCoverageGuest() will return false.
If the value is true then, it proceed to the next level which is checkout. If the value is false, the screen will display toast error message that the selected restaurant is not under coverage.
Right now, every this coming out from this function checkCoverageGuest() as false.
Here is my code.
private boolean checkCoverageGuest() {
try {
String url;
if (appPrefs.getLanguage().equalsIgnoreCase("ar"))
url = LinksConstants.TEST_SERVER_URL
+ LinksConstants.SEARCH_COVERAGE_AREA;
else
url = LinksConstants.TEST_SERVER_URL
+ LinksConstants.SEARCH_COVERAGE_AREA;
Intent startingIntent = getIntent();
city_id = getIntent().getStringExtra("id");
RequestParams params = new RequestParams();
params.put("area", city_id);
NetworkRestClient.post(url, params, new JsonHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
progressActivity.showLoading();
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
progressActivity.showContent();
JSONObject[] restaurants_arr = null;
hasCoverageGuest = true;
try {
if (response != null) {
JSONArray restaurants = response.getJSONArray("restaurants");
// if restaurants deliver to that area
if (!restaurants.getString(0).equals("null")) {
restaurants_arr = new JSONObject[restaurants.length()];
int has_coverage = 1; // assume coverage is there..
for (int j = 0; j < Utils.cart_restaurants.size(); j++) {
RestaurantModel restaurant = Utils.cart_restaurants.get(j);
String restaurantCartID = restaurant.getId();
boolean found = false;
for (int i = 0; i < restaurants.length(); i++) {
restaurants_arr[i] = restaurants.getJSONObject(i);
String restaurantID = restaurants_arr[i].get("restaurant_id").toString();
if (restaurantCartID.equals(restaurantID)) {
found = true;
break;
}
} //end of inner for
if (found == false) {
Toast.makeText(CheckoutActivity.this, "There is no coverage for the Selected Area ", Toast.LENGTH_SHORT).show();
hasCoverageGuest = false;
break;
}
}
//end of outer for
} //end of if
else //if restaurants don't deliver to that area
{
hasCoverageGuest = false;
}
} // end of if response != null
} // end of try
catch (Exception ex) {
GSLogger.e(ex);
showError();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable throwable) {
super.onFailure(statusCode, headers, errorResponse, throwable);
showError();
if (AppConstants.DEBUG_MODE)
showToast(errorResponse);
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
showError();
}
});
} catch (Exception ex) {
GSLogger.e(ex);
showError();
}
return hasCoverageGuest;
}
You need to have a callback to specify success or failure. one way to do that is using interface.
public interface notifyGuestCoverage {
void hasCoverage(int status);
}
in onSuccess,
if (!restaurants.getString(0).equals("null")) {
notifyGuestCoverageObj.hasCoverage(true);
}
This interface will be implemented by class which requires value of has coverage. for ex,
class Example implements notifyGuestCoverage{
void hasCoverage(int status){
//your code
}
}
Your private boolean checkCoverageGuest() method returns before public void onSuccess() is executed, this is the reason for checkCoverageGuest() always returning false.
If you need to execute something after you get the hasCoverageGuest good value then excute it inside onSucess()

Java Android AsyncHttpClient convert byte[]responseBody to InputStream

I want to create a methos which return a InputStream I did this :
public static InputStream sendGetDataRequest(Context context,
String version, String power, String lon, String lat, String radius) throws MalformedURLException, ConnectTimeoutException, IOException
{
AsyncHttpClient client = new AsyncHttpClient();
String url = Util.getServerUrl(context) + "/GetData";
// ContentValues values=new ContentValues();
RequestParams values = new RequestParams();
values.put("token", String.valueOf(E_Gps.TOKEN));
values.put("xml", login_xml);
StringEntity entity = null;
try {
entity = new StringEntity(values.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
entity.setContentType(new BasicHeader("Content-Type","application/xml"));
final InputStream[] is = new InputStream[1];
final InputStream inputStream;
client.post(context,url,values , new AsyncHttpResponseHandler(Looper.getMainLooper()) {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.e("success_noti", new String(responseBody) + "");
is[0] = new ByteArrayInputStream(responseBody);
Log.e("Status " , statusCode + " ");
Log.e("is" , convertStreamToString(is[0]));
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.e("success_noti", new String(responseBody) + "");
Log.e("Status " , statusCode + " ");
}
});
return is[0];
}
And I have probleme when I return is[0] is a null but when I log in onSuccess :
Log.e("is" , convertStreamToString(is[0]));
is not null why I have null object is[0] ?
Because client.post is an asynchronous call while return is[0] is a synchronous. This means that is[0] is null as long as the async call is not done yet. One way to solve is by making sendGetDataRequest return void and instead accepts a callback e.g.
public static void sendGetDataRequest(final YourCallback callback, ...)
Create a new Interface named YourCallback
public interface YourCallback{
void onSuccess(String string);
void failure();
}
And use that Callback inside the async method
client.post(context,url,values , new AsyncHttpResponseHandler(Looper.getMainLooper()) {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
callback.onSuccess(convertStreamToString(is[0]));
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
callback.onFailure();
}
}
Finally you call your static method like this
sendGetDataRequest(new YourCallback(){/* Override the methods */}, ...);
By the way you could also use AsyncTask from the android package which does everything above. It's personal preference.

Android Loopj's Async JsonObject reponse is cast to Objectid failed

I'm relatively new in Android & Restful API programming, so I might be making some stupid mistakes. However I am facing this from my response JsonObject:
Cast to ObjectId failed for value \"login\" at path \"_id\" for model \"User\"","name":"CastError","stringValue":"\"login\"","kind":"ObjectId","value":"login","path":"_id"}
I have tested my Rest API on Postman and everything returns just fine. The Restful API is written in Node.js and Express.
The Rest API is suppose to return a status, userid, and message to let the app know if the user logged in using the right username and password. The login works fine and it returns me a 200 which allows the app to login and keep it logged in using a session. However, I can't get anything from the response JsonObject to get the userid for my next step in displaying user information.
(Target Android API 23)
Code:
Restful.Java
public class RestClient {
private static final String BASE_URL = "http://10.0.2.2:8000/api/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler){
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler){
client.post(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl){
Log.d("URL: ", BASE_URL+relativeUrl);
return BASE_URL + relativeUrl;
}
}
LoginActivity.Java (Only the login part)
public void checkLoginDB(final RequestParams params, final String username){
prgDialog.show();
RestClient.post("user/login", params, new JsonHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
Log.d("StatusCode: ", "Code "+ statusCode);
try {
if (statusCode == 200) {
Toast.makeText(getApplicationContext(), "Logged In!", Toast.LENGTH_LONG).show();
session.createLoginSession(username);
Log.d("Log: ", "what " + response);
navigatetoHomeActivity();
}
} catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.d("StatusCode: ", "Code "+ statusCode);
prgDialog.hide();
Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_LONG).show();
}
});
}
Restful API's Server.js
router.post('/user/login', function(req, res){
var username = req.body.username;
var password = req.body.password;
if(username.length > 0 && password.length > 3){
User.findOne({username: username, password: password}, function(err, user){
if(err)
res.json({statusCode: 0, message: "login error: " + err});
if(!user)
res.json({statusCode: 0, message: "Not Found"});
res.json({statusCode: 200, userid: user._id, message: "Login Sucessful"});
})
} else {
res.json({statusCode: 0, message: "Invalid Fields"});
}
});
app.use('/api', router)
User.js (Defined schema)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: String,
password: String,
firstname: String,
lastname: String,
agentID: Number,
email: String,
phone: Number
});
module.exports = mongoose.model('User', UserSchema);
Whenever you want to Login the user and want user details in return use post() method.
in your code the second method is not post, so change client.get() to client.post()
like this public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler){
client.post(getAbsoluteUrl(url), params, responseHandler);
}

Categories

Resources