I have the main activity where i load all my markers from the database into a List and then i add them in my map.
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
MainActivity.this.mapboxMap = mapboxMap;
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
List<Feature> symbolLayerIconFeatureList = new ArrayList<>();
for(int i = 0; i < jsonArray.length(); i++){
JSONObject crag = jsonArray.getJSONObject(i);
String nome = crag.getString("nome");
String tipo = crag.getString("tipo");
Double lng = crag.getDouble("longitudine");
Double lat = crag.getDouble("latitudine");
symbolLayerIconFeatureList.add(Feature.fromGeometry(Point.fromLngLat(lng,lat)));
symbolLayerIconFeatureList.get(i).addStringProperty("NAME_PROPERTY_KEY", nome);
symbolLayerIconFeatureList.get(i).addStringProperty("TYPE_KEY", tipo);
}
mapboxMap.setStyle(new Style.Builder().fromUri("mapbox://styles/mapbox/streets-v11")
.withSource(new GeoJsonSource(SOURCE_ID,
FeatureCollection.fromFeatures(symbolLayerIconFeatureList)))
.withLayer(new SymbolLayer(LAYER_ID, SOURCE_ID)
.withProperties(
iconImage(get("TYPE_KEY")),
iconAllowOverlap(true),
iconIgnorePlacement(true),
textOffset(new Float[]{0f,-2.5f}),
textIgnorePlacement(true),
textAllowOverlap(true),
textField(get("NAME_PROPERTY_KEY"))
)
), new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
mapboxMap.addOnMapClickListener(MainActivity.this);
mapboxMap.getUiSettings().setLogoEnabled(false);
mapboxMap.getUiSettings().setAttributionEnabled(false);
enableLocationComponent(style);
}
});
} catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
mapView.addOnStyleImageMissingListener(new MapView.OnStyleImageMissingListener() {
#Override
public void onStyleImageMissing(#NonNull String id) {
if(id.equals("Falesia")){
addImage(id, R.drawable.icona_falesia);
} else{
addImage(id, R.drawable.icon_gym);
}
}
});
}
I can't figure how to make them clickable
I saw the documentation and the example and maybe i have to implement onMapClick method, but i don't know what put in it.
Does anyone know how to implement it or other way to make them clickable?
Thank you.
You can add a map click listener in your onMapReady-callback. In your onMapClick-method you set up a query at the selected point to see if there are any features in the symbollayer at that location. Then you get a list of features in that point that you can use. Here's a very condensed version of what I'm using:
private void handleMapClick(LatLng point){
if (myMapboxMap != null){
final PointF screenPoint = myMapboxMap.getProjection().toScreenLocation(point);
List<Feature> features = myMapboxMap.queryRenderedFeatures(screenPoint, SYMBOL_LAYER_ID);
if (!features.isEmpty()) {
//do stuff with features in feature list
}
}
}
I am using recreate and refresh() to refresh page every minute but it double refreshes. First refresh is after 1minute, and the next refresh is after 2 sec first refresh.
i have tried changing the code inside refresh but didnt work.
private void loadalltrolley(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, PRODUCT_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products = new JSONArray(response);
for(int i =0;i<products.length();i++){
JSONObject productObject = products.getJSONObject(i);
String gate_no = productObject.getString("gate_no");
String dock_name = productObject.getString("dock_name");
String dock_desc = productObject.getString("dock_desc") ;
int flight_arrival = productObject.getInt("flight_arrival");
int trolley_count = productObject.getInt("trolley_count");
Product product = new Product(gate_no,dock_name,dock_desc,flight_arrival,trolley_count);
allterminalList.add(product);
}
allterminaladapter = new ProductAdapter(alert.this,allterminalList);
recyclerView.setAdapter(allterminaladapter);
int count = allterminaladapter.getItemCount();
int i =0;
if (count>0)
{
displayNotification();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(alert.this,error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
refresh(60000);
}
public void refresh(int milliseconds){
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
recreate();
}
};
handler.postDelayed(runnable,milliseconds);
}
I want it to refresh 1 time only and not double refresh. I want to refresh the application after 1minute only.
Hello fellow developer,
I created a map using google map activity in android studio and my class extending AppCompactActivity because i want to use Toolbar. When running onMapReady called twice (i try it using Log.d) but when i am change AppCompactActivity to FragmentActivity it only called once.
Updated Code :
public class Maps extends AppCompatActivity implements OnMapReadyCallback, DatePickerDialog.OnDateSetListener, View.OnCreateContextMenuListener {
Context context;
private GoogleMap mMap;
private LocationManager locationManager;
Location location;
TextView eta, distance, tvfrom, tvto;
EditText txtTruck;
AutoCompleteTextView search;
Bitmap keraniMarker, truck, arrowup, puninar;
BitmapDescriptor bdfKerani = null, bdfTruck = null, bdfArrow = null, bdfPuninar = null;
CardView cardFind;
Button btnfind;
SwitchCompat swTraffic;
/////////////////////
static SwitchCompat swProgress;
TextView tvFilter;
ListView lvOrderTruck;
EditText txtSearch;
ArrayList<Order_Truck_SetGet> complete = new ArrayList<>();
ArrayList<Order_Truck_SetGet> onGoing = new ArrayList<>();
String custCode = "nocust";
static String nopol_to_map = "all";
private Order_Truck_Adapter adapter_order_truck;
////////////////////
ArrayList<String> nop = new ArrayList<>();
ArrayList<LastLocationSetterGetter> lastloc = new ArrayList<>();
ArrayList<LatLng> livelatlng = new ArrayList<>();
ArrayList<startmark> arstart = new ArrayList<>();
ArrayList<String> project = new ArrayList<>();
String lokasi, nama, time, speed, statustitle;
TextView namadet, lokasidet, timedet, txtspeed, txtSPK, txtOMpils, txtOMccms, txtCust, txtDriver, txtRute, tvSiMbl, txtSiMbl;
ImageView call, sms, wa;
String telp = "+6281280688872";
LinearLayout llSpk, llOMpils, llOMccms, llCust, llDriver, llRute, llSiMbl;
private ProgressDialog pDialog;
private Dialog dashDialog, listOrderDialog;
int FLAG_START_DATE = 0;
int FLAG_END_DATE = 1;
int flag = -1;
int flag_menu = 0;
private long mLastClickTime = 0;
static final int LOCATION = 1;
static final int WRITE_EXTERNAL = 2;
static final int CALL_PHONE = 3;
static final int SEND_SMS = 4;
int PERMISSION_ALL = 1;
Marker lastmark = null;
Marker startmark = null;
Marker track_arrow = null;
String pilih = Order_Truck.nopol_to_map;
String projectselect = "all";
LinearLayout llnopol, lldate, lllokasi;
ImageView nopol_arrow, date_arrow, lokasi_arrow;
ListView lvTruck;
ArrayList<Dashboard_Truck_SetGet> dastruck = new ArrayList<>();
private Dashboard_Truck_adapter adapter;
private DisplayMetrics metrics;
private boolean mAscendingOrder[] = {true, true, true};
String classname = this.getClass().getSimpleName();
Thread live = new Thread();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//set for check permission
String[] PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE, Manifest.permission.SEND_SMS};
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
distance = (TextView) findViewById(R.id.DISTANCE);
eta = (TextView) findViewById(R.id.ETA);
search = (AutoCompleteTextView) findViewById(R.id.search);
cardFind = (CardView) findViewById(R.id.cardFind);
tvfrom = (TextView) findViewById(R.id.txtFrom);
tvto = (TextView) findViewById(R.id.txtTo);
btnfind = (Button) findViewById(R.id.btnFind);
swTraffic = (SwitchCompat) findViewById(R.id.swTraffic);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Authenticating...");
pDialog.setCancelable(false);
cekOverlay();
project.add("All Project");
project.add("EXIM");
//set logo for marker
//option 1
BitmapDrawable bitmap_kerani = (BitmapDrawable) getResources().getDrawable(R.drawable.truck);
Bitmap kerani_ico = bitmap_kerani.getBitmap();
keraniMarker = Bitmap.createScaledBitmap(kerani_ico, 100, 100, false);
bdfKerani = BitmapDescriptorFactory.fromBitmap(keraniMarker);
BitmapDrawable bitmap_puninar = (BitmapDrawable) getResources().getDrawable(R.drawable.marker_puninar);
Bitmap puninar_ico = bitmap_puninar.getBitmap();
puninar = Bitmap.createScaledBitmap(puninar_ico, 150, 150, false);
bdfPuninar = BitmapDescriptorFactory.fromBitmap(puninar);
BitmapDrawable bitmap_truck = (BitmapDrawable) getResources().getDrawable(R.drawable.flat_truck);
Bitmap truck_icon = bitmap_truck.getBitmap();
truck = Bitmap.createScaledBitmap(truck_icon, 70, 100, false);
bdfTruck = BitmapDescriptorFactory.fromBitmap(truck);
BitmapDrawable bitmap_arrow = (BitmapDrawable) getResources().getDrawable(R.drawable.green_arrow);
Bitmap arrow_up = bitmap_arrow.getBitmap();
arrowup = Bitmap.createScaledBitmap(arrow_up, 70, 50, false);
bdfArrow = BitmapDescriptorFactory.fromBitmap(arrowup);
tvfrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDate();
flag = FLAG_START_DATE;
}
});
tvto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDate();
flag = FLAG_END_DATE;
}
});
btnfind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (tvfrom.getText().length() == 0) {
Toast.makeText(getApplicationContext(), "From date must be filled", Toast.LENGTH_SHORT).show();
} else if (tvto.getText().length() == 0) {
Toast.makeText(getApplicationContext(), "To date must be filled", Toast.LENGTH_SHORT).show();
} else if (pilih.isEmpty()) {
Toast.makeText(getApplicationContext(), "Police number must be choosen", Toast.LENGTH_SHORT).show();
} else {
getcarloc(pilih, projectselect);
}
}
});
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-3.503399, 112.423781), 4.0f));
swTraffic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
swTraffic.setText("Traffic ON ");
mMap.setTrafficEnabled(true);
} else {
mMap.setTrafficEnabled(false);
swTraffic.setText("Traffic OFF ");
}
}
});
//GPS LAST POSITION
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
search.setText("");
}
});
Log.d("pilihan", pilih + " ^.^");
getNopol(projectselect);
getcarloc(pilih, projectselect);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 15.0f));
return false;
}
});
}
public void getcarloc(final String nopol, final String project) {
if (flag_menu != 2) {
mMap.clear();
livelatlng.clear();
lastloc.clear();
}
Log.d("PILIH2", nopol);
Log.d("LIVESTATUS", String.valueOf(live.getState()));
String url;
showpDialog();
if (flag_menu == 1) {
url = Config.GET_LOCATION_HISTORICAL;
} else {
url = Config.GET_LAST_LOCATION;
}
mMap.addMarker(new MarkerOptions().position(new LatLng(-6.172172, 106.941581)).title("Puninar Jaya Cakung").snippet("Puninar Jaya Cakung").icon(bdfPuninar));
mMap.addMarker(new MarkerOptions().position(new LatLng(-6.128611, 106.941747)).title("Puninar Jaya Nagrak").snippet("Puninar Jaya Nagrak").icon(bdfPuninar));
mMap.addMarker(new MarkerOptions().position(new LatLng(-6.029199, 106.085906)).title("Puninar Jaya Cilegon").snippet("Puninar Jaya Cilegon").icon(bdfPuninar));
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
hidepDialog();
try {
JSONObject json = new JSONObject(response);
JSONArray jsonArray = json.getJSONArray("data");
if (String.valueOf(jsonArray).equals("[]")) {
hidepDialog();
if (flag_menu == 1) {
Toast.makeText(getApplicationContext(), "There is No Trip History From " + tvfrom.getText() + " Until " + tvto.getText() + " for " + pilih, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "There is No Data / Location For " + pilih, Toast.LENGTH_SHORT).show();
}
} else {
Log.e("JSONARRAY", String.valueOf(jsonArray));
String vehicle_id = null,
vehicle_number = null;
for (int i = 0; i < jsonArray.length(); i++) {
//Get data last location or live tracking
JSONObject obj = jsonArray.getJSONObject(i);
String position_id = obj.getString("position_id");
if (flag_menu != 1) {
vehicle_id = obj.getString("vehicle_id");
vehicle_number = obj.getString("vehicle_number");
}
String date_time = obj.getString("date_time");
Double longitude = Double.parseDouble(obj.getString("longitude")) / 10000000;
Double latitude = Double.parseDouble(obj.getString("latitude")) / 10000000;
String speed = obj.getString("speed");
String course = obj.getString("course");
String street_name = obj.getString("street_name");
String kecamatan = obj.getString("kecamatan");
String kabupaten = obj.getString("kabupaten");
if (flag_menu != 1) {
lastloc.add(new LastLocationSetterGetter(position_id, vehicle_id, vehicle_number,
date_time, longitude, latitude, speed, course, street_name, kecamatan, kabupaten));
} else {
lastloc.add(new LastLocationSetterGetter(position_id, pilih,
date_time, longitude, latitude, speed, course, street_name, kecamatan, kabupaten));
}
LatLng latLng = new LatLng(latitude, longitude);
if (lastmark != null) {
lastmark.remove();
}
//Log.i("InfoSize", String.valueOf(lastloc.size()));
//create marker for live tracking
if (flag_menu != 0) {
livelatlng.add(latLng);
if (startmark == null) {
//create start marker
startmark = mMap.addMarker(new MarkerOptions().position(latLng).title("Start").snippet(vehicle_number).icon(bdfKerani));
arstart.add(new startmark(street_name, kecamatan, kabupaten, vehicle_number, date_time, speed));
} else {
// create live tracking marker
lastmark = mMap.addMarker(new MarkerOptions().position(latLng).title(pilih).snippet(vehicle_number).icon(bdfTruck));
lastmark.setFlat(true);
lastmark.setRotation(Float.parseFloat(course));
if (lastloc.size() > 2) {
track_arrow = mMap.addMarker(new MarkerOptions()
.position(new LatLng(lastloc.get(lastloc.size() - 2).getLatitude(), lastloc.get(lastloc.size() - 2).getLongitude()))
.title(lastloc.get(lastloc.size() - 2).getPosition_id())
.snippet(lastloc.get(lastloc.size() - 2).getVehicle_number())
.icon(bdfArrow));
track_arrow.setFlat(true);
track_arrow.setRotation(Float.parseFloat(lastloc.get(lastloc.size() - 2).getCourse()));
}
}
if (livelatlng.size() > 1) {
//int ap22 = getResources().getColor(R.color.fbutton_color_wet_asphalt);
int ap23 = ContextCompat.getColor(getApplicationContext(), R.color.fbutton_color_belize_hole);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(livelatlng.get(livelatlng.size() - 2), livelatlng.get(livelatlng.size() - 1))
.width(10)
.color(ap23));
}
} else {
//create marker for last location
MarkerOptions marker = new MarkerOptions().position(latLng).title(vehicle_number).snippet(vehicle_number).icon(bdfKerani);
mMap.addMarker(marker);
}
}
Log.d("TOTALRECORD", String.valueOf(livelatlng.size()));
if (nopol != "all") {
Log.e("lastloc", String.valueOf(lastloc.size()));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastloc.get(lastloc.size() - 1).getLatitude(), lastloc.get(lastloc.size() - 1).getLongitude()), 16.0f));
//cardFind.setVisibility(View.VISIBLE);
} else {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-4.979218, 107.950524), 5.0f));
}
clickmap();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("ERRORCATCH", String.valueOf(e));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidepDialog();
Log.e("ERROR", String.valueOf(error));
String message = null;
if (error instanceof NetworkError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof ServerError) {
message = "The server could not be found. Please try again after some time!!";
} else if (error instanceof AuthFailureError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof ParseError) {
message = "Parsing error! Please try again after some time!!";
} else if (error instanceof NoConnectionError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof TimeoutError) {
message = "Connection TimeOut! Please check your internet connection.";
}
Log.e("VOLLEYERROR", message);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("prm_1", nopol);
params.put("project", project);
if (flag_menu == 1) {
params.put("from", tvfrom.getText().toString());
params.put("to", tvto.getText().toString());
}
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String credentials = "admin_it" + ":" + "admin123";
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
public void getNopol(final String project) {
Log.d("PILIHNOPOL", "NOPOL");
//Get all police Number
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.GET_NOPOL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
nop.clear();
if (flag_menu == 0) {
nop.add("all");
}
try {
JSONObject json = new JSONObject(response);
JSONArray jsonArray = json.getJSONArray("nopol");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String plat = obj.getString("vehicle_number").replace(" ", "");
nop.add(plat);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(Maps.this, android.R.layout.simple_list_item_1, nop);
search.setAdapter(arrayAdapter);
search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pilih = parent.getItemAtPosition(position).toString();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
mMap.clear();
startmark = null;
livelatlng.clear();
arstart.clear();
lastloc.clear();
if (flag_menu != 1) {
getcarloc(pilih, projectselect);
}
//Live Tracking selected
if (flag_menu == 2) {
if (live.getState().equals("TIMED_WAITING")) {
live.interrupt();
try {
live.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
live = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000 * 76);
runOnUiThread(new Runnable() {
#Override
public void run() {
getcarloc(pilih, projectselect);
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
live.start();
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("NORESPONSE", String.valueOf(error));
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("project", project);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String credentials = "admin_it" + ":" + "admin123";
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
}
This is my library
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.0'
compile 'com.android.support:design:25.3.0'
compile 'com.android.support:cardview-v7:25.3.0'
compile 'com.google.android.gms:play-services-maps:10.2.1'
compile 'com.google.android.gms:play-services-location:10.2.1'
compile 'com.akexorcist:googledirectionlibrary:1.0.4'
compile 'cn.pedant.sweetalert:library:1.3'
compile 'com.android.volley:volley:1.0.0'
compile 'com.wdullaer:materialdatetimepicker:2.3.0'
compile 'com.android.support.constraint:constraint-layout:1.0.1'
testCompile 'junit:junit:4.12'
}
Your handling of the Google Map inside your onCreate() method seems slightly different than what I have used and seen. Try using this code instead:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this); // don't pass Maps.this
// rest of your code here
}
My hunch is that somehow you were binding the listener twice, though I can't prove this without trying to duplicate your actual code locally.
Firstly, i'm fetching some data from server database and getting some addresses which i'm reversing to location latitude and longitude, so i can calculate after that distance between my location latlng and theirs.
But for some reason Activity freezes at loading data and list is loading very slow with this feature. This is how i'm calculating distance between two location:
AndroidNetworking.get(AppConfig.GET_FIELDS_ORDER_BY_CITY.replace("city", tvCurrentLocation.getText().toString()))
.setPriority(Priority.IMMEDIATE)
.build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
mFieldList.clear();
try {
if (!response.getBoolean("error")) {
JSONArray fieldsArray = response.getJSONArray("fields");
for (int i = 0; i < fieldsArray.length(); i++) {
JSONObject fieldObj = fieldsArray.getJSONObject(i);
Field field = new Field();
...
field.setCertificate(fieldObj.getString("certificate"));
Log.d("Location", fieldObj.getString("address"));
// If i delete from here
if (!fieldObj.getString("address").isEmpty()) {
LatLng latLng = AppUtils.getLocationFromAddress(SearchActivityV2.this,
fieldObj.getString("address"));
float dist = AppUtils.distFrom(44.8029925f, 20.495337f, (float) latLng.latitude, (float) latLng.longitude);
DecimalFormat df = new DecimalFormat("####0.0");
if (dist > 1000) {
double distance = AppUtils.calculationByDistance(new LatLng(44.8029925, 20.495337), latLng);
field.setDistance(df.format(distance) + " km");
} else {
String newValue = Double.toString(Math.floor(dist));
field.setDistance(newValue + " m");
}
} else {
field.setDistance("1000");
}
mFieldList.add(field);
}
// to here, list would load immediately, so
// something is not right with this
mFieldsListAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
Log.e(getClass().getSimpleName(), e.getMessage());
e.printStackTrace();
}
}
#Override
public void onError(ANError anError) {
Log.e(getClass().getSimpleName(), anError.getMessage());
}
});ield.setDistance(df.format(distance) + " km");
} else {
String newValue = Double.toString(Math.floor(dist));
field.setDistance(newValue + " m");
}
Any suggestions or tips what should i do? Thank you!
"onResponse" method works on main thread, So data parsing and heavy calculations may freeze app's UI thread.
Try to move all your parsing code and calculations to AsyncTask's "doInBackground" and update your adapter in "onPostExecute" because you must be on ui thread to perform this action.
code example:
private class ResponseParser extends AsyncTask<JSONObject, Void, Void> {
#Override
protected Void doInBackground(JSONObject... params) throws JSONException {
mFieldList.clear();
JSONArray fieldsArr = params[0].getJSONArray("fields");
if (!response.getBoolean("error")) {
JSONArray fieldsArray = response.getJSONArray("fields");
for (int i = 0; i < fieldsArray.length(); i++) {
JSONObject fieldObj = fieldsArray.getJSONObject(i);
Field field = new Field();
...
field.setCertificate(fieldObj.getString("certificate"));
Log.d("Location", fieldObj.getString("address"));
// If i delete from here
if (!fieldObj.getString("address").isEmpty()) {
LatLng latLng = AppUtils.getLocationFromAddress(SearchActivityV2.this,
fieldObj.getString("address"));
float dist = AppUtils.distFrom(44.8029925f, 20.495337f, (float) latLng.latitude, (float) latLng.longitude);
DecimalFormat df = new DecimalFormat("####0.0");
if (dist > 1000) {
double distance = AppUtils.calculationByDistance(new LatLng(44.8029925, 20.495337), latLng);
field.setDistance(df.format(distance) + " km");
} else {
String newValue = Double.toString(Math.floor(dist));
field.setDistance(newValue + " m");
}
} else {
field.setDistance("1000");
}
mFieldList.add(field);
}
// to here, list would load immediately, so
// something is not right with this
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mFieldsListAdapter.notifyDataSetChanged();
}
}
Hope it helps!
I'm getting few values from a web service. The values keep changing every time I get the value from web service. I use a TimerTask in Serviceto get the values repeatedly.
I can't think of how to check if the value I got is the same as before.
public ArrayList getCo_ordinates(String deviceId) {
String URL_CO_ORDINATES = "http://192.168.1.42:8080/image/getDevicePosition?deviceId=" + deviceId;
// trimCache(getApplicationContext());
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.start();
final JsonArrayRequest request = new JsonArrayRequest(URL_CO_ORDINATES, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
X = response.getJSONObject(i).getString("xCoordinate");
Y = response.getJSONObject(i).getString("yCoodinate");
System.out.println("xCoordinate" + X);
System.out.println("yCoodinate" + Y);
// tap();
addTap(Integer.parseInt(X), Integer.parseInt(Y));
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context,""+e,Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), "Could Not connect to server", Toast.LENGTH_LONG).show();
}
});
requestQueue.add(request);
return null;
}
X = response.getJSONObject(i).getString("xCoordinate");
Y = response.getJSONObject(i).getString("yCoodinate");
System.out.println("xCoordinate" + X);
System.out.println("yCoodinate" + Y);
if(prev_x==X)
{
Log.d("same","value");
}
else
{
Log.d("different","value");
}
prev_x=X;
prev_y=Y;