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.
Related
Single marker is moving perfectly but when adding more than one marker it is not working fine.
StringRequest stringRequest = new StringRequest(Request.Method.GET, Url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("GET_ASSIGNED_PROJECT", response);
try {
progressDialog.dismiss_dialog();
JSONObject jsonObject1 = new JSONObject(response);
message = jsonObject1.getString("message");
if (message.equals("success")) {
startTimer();
JSONArray jsonArray = jsonObject1.getJSONArray("responseMessg");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
ManagementHomeModel homePageModel = new ManagementHomeModel();
homePageModel.setRegistrationid(jsonObject.getString("Registrationid"));
homePageModel.setName(jsonObject.getString("Name"));
homePageModel.setImageUrl(jsonObject.getString("ImageUrl"));
homePageModel.setLatitude(Double.parseDouble(jsonObject.getString("Latitude")));
homePageModel.setLongitude(Double.parseDouble(jsonObject.getString("Longitude")));
double weblat = jsonObject.getDouble("Latitude");
double weblong = jsonObject.getDouble("Longitude");
latLng = new LatLng(weblat, weblong);
Glide.with(getContext()).load(ServiceUrl.IMAGE_OPEN_URL + jsonObject.getString("ImageUrl")).asBitmap().fitCenter().into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
webmarker = new MarkerOptions().position(new LatLng(weblat, weblong)).icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(mCustomMarkerView, bitmap)));
cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
mMap.animateCamera(cameraUpdate);
finalmarker = mMap.addMarker(webmarker);
allManagementHomeModels.add(homePageModel);
allHashmarker.put(finalmarker, homePageModel);
}
});
}
} else {
JSONObject object = jsonObject1.getJSONObject("responseMessg");
String responceresult = object.getString("ResposeResult");
Toast.makeText(getContext(), responceresult, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", error.getMessage());
progressDialog.dismiss_dialog();
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
final long start = SystemClock.uptimeMillis();
final Interpolator interpolator = new AccelerateDecelerateInterpolator();
final float durationInMs = 3000;
final boolean hideMarker = false;
handler.post(new Runnable() {
long elapsed;
float t;
float v;
#Override
public void run() {
moveMarker = (new ArrayList<Marker>(allHashmarker.keySet())).get(pos);
ManagementHomeModel model = (new ArrayList<ManagementHomeModel>(allHashmarker.values())).get(pos);
startPosition = moveMarker.getPosition();
elapsed = SystemClock.uptimeMillis() - start;
t = elapsed / durationInMs;
v = interpolator.getInterpolation(t);
LatLng currentPosition = new LatLng(
startPosition.latitude * (1 - t) + (finalPosition.getLatitude()) * t,
startPosition.longitude * (1 - t) + (finalPosition.getLongitude()) * t);
moveMarker.setPosition(currentPosition);
if (t < 1) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
if (hideMarker) {
finalmarker.setVisible(false);
} else {
finalmarker.setVisible(true);
}
}
}
});
}
not able to track all the marker at the same time. I need to track all the markers at the same time like ola cab. Only single marker can be able to track, not more than one. Kindly help me to fix this issue.
Add all markers in a list when adding a marker in google map. Then whenever you need to update the position of a marker just find the current marker from the list and update position.
I want to draw route on map when I place the destination marker from the Places AutoComplete search bar. As soon as I select the Drop location from Auto Complete, I want the route. I have seen some examples of drawing path but can't find any via the Places Autocomplete. My map and Places Autocomplete are working properly. How do I do it?
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), "my_api_ke");
}
/*Map Initialisation*/
mv = findViewById(R.id.Gmapview);
mv.onCreate(savedInstanceState);
mv.getMapAsync(this);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = lm.getBestProvider(new Criteria(), false);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
checkLocationPermission();
enableMyLocationIfPermitted();
//Initialize AutoCompleteSupportFragment
//Pickup Search Bar
supportFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.pickup);
supportFragment1 = (AutocompleteSupportFragment) getSupportFragmentManager()
.findFragmentById(R.id.drop);
//Initialize the Fields to get Latitude and Langitude and name of the selected place.
supportFragment.setPlaceFields(Arrays.asList(Place.Field.LAT_LNG, Place.Field.NAME));
supportFragment1.setPlaceFields(Arrays.asList(Place.Field.LAT_LNG, Place.Field.NAME));
//Placing Pickup Marker
supportFragment.setOnPlaceSelectedListener(newPlaceSelectionListener(){
#Override
public void onPlaceSelected(#NonNull Place pickup) {
Log.i("PickUP", "Place: " + pickup.getName() + ", ");
String name = pickup.getName();
LatLng latLng = pickup.getLatLng();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(name);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
gm.addMarker(markerOptions);
gm.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
#Override
public void onError(#NonNull Status status) {
Log.i("pickup", "An error occurred: " + status);
}
});
//Placing Drop Marker
supportFragment1.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(#NonNull Place drop) {
Log.i("Drop", "Place: " + drop.getName() + ", ");
String name = drop.getName();
LatLng latLng = drop.getLatLng();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
gm.addMarker(markerOptions);
gm.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
#Override
public void onError(#NonNull Status status) {
Log.i("drop", "An error occurred: " + status);
}
});
}
Supposing your LatLng objects are correct and you only need to draw routes, here what you should do
Create a Helper class called DirectionsJSONParser that will later decode your polyline and give you a list of latitude longitude objects.
Here is the link for that class DirectionsJSONParser
For RetrofitClient those are the imports make sure you add them
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
Add this to your build.gradle(app) file
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
Create a retrofit client
//this is a singleton of Retrofit
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if(retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
}
//return retrofit object
return retrofit;
}
}
Next create a google API interface
public interface IGoogleAPI {
#GET
Call<String> getPath(#Url String url);
}
Create a Common class
public class Common {
public static String baseURL = "https://maps.googleapis.com/";
public static IGoogleAPI getGoogleAPI() {
return RetrofitClient.getClient(baseURL).create(IGoogleAPI.class);
}
}
Last but not least , declare a variable in your activity
IGoogleAPI mService;
Initialize that variable in onCreate
mService = Common.getGoogleAPI();
Create a method to draw routes
private void getDirection() {
String requestAPI;
try {
requestAPI = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_preference=less_driving&" +
"origin=" + pickupMarker.getLatitude() + "," + pickupMarker.getLongitude() +
"&destination=" + dropMarker.getLatitude() + "," + dropMarker.getLongitude() + "&" +
"key=" + getResources().getString(R.string.google_direction_apis);
mService.getPath(requestAPI)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, retrofit2.Response<String> response) {
try {
new ParserTask().execute(response.body().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Don't forget
To add retrofit dependencies in your build.gradle
To change your API_KEY in the requestString.
It's a long code so if you have any problem tell me .
Call this function getDirection() after you get the drop location.
EDIT
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
ProgressDialog mDialog = new ProgressDialog(NavigationTracking.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog.setMessage("Executing...");
mDialog.show();
}
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... strings) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(strings[0]);
DirectionJsonParser parser = new DirectionJsonParser();
routes = parser.parse(jObject);
} catch (JSONException e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> lists) {
mDialog.dismiss();
ArrayList points = null;
PolylineOptions polylineOptions = null;
Toast.makeText(NavigationTracking.this, "" + lists.size(), Toast.LENGTH_SHORT).show();
for (int i = 0; i < lists.size(); i++) {
points = new ArrayList();
polylineOptions = new PolylineOptions();
List<HashMap<String, String>> path = lists.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
polylineOptions.addAll(points);
polylineOptions.width(10);
polylineOptions.color(Color.RED);
// the shortest line between two points
polylineOptions.geodesic(true);
}
if (polylineOptions != null) {
direction = mMap.addPolyline(polylineOptions);
}
}
}
Declare
private Polyline direction;
And add this test before calling getDirection()
if (direction != null)
direction.remove();
EDIT 2
Declare 2 LatLng variables before onCreate() like this :
LatLng pickupLoc;
LatLng dropLoc;
Then when you are picking places your code become like this
//Placing Pickup Marker
supportFragment.setOnPlaceSelectedListener(newPlaceSelectionListener(){
#Override
public void onPlaceSelected(#NonNull Place pickup) {
Log.i("PickUP", "Place: " + pickup.getName() + ", ");
String name = pickup.getName();
pickupLoc = pickup.getLatLng();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(pickupLoc );
markerOptions.title(name);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
gm.addMarker(markerOptions);
gm.moveCamera(CameraUpdateFactory.newLatLngZoom(pickupLoc, 11));
}
#Override
public void onError(#NonNull Status status) {
Log.i("pickup", "An error occurred: " + status);
}
});
//Placing Drop Marker
supportFragment1.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(#NonNull Place drop) {
Log.i("Drop", "Place: " + drop.getName() + ", ");
String name = drop.getName();
dropLoc = drop.getLatLng();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(dropLoc );
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
gm.addMarker(markerOptions);
gm.moveCamera(CameraUpdateFactory.newLatLngZoom(dropLoc, 11));
//here you test if your locations aren't null call getDirection() like this
if (pickupLoc != null && dropLoc != null) {
if (direction != null)
direction.remove();
getDirection();
}
}
#Override
public void onError(#NonNull Status status) {
Log.i("drop", "An error occurred: " + status);
}
});
So the answer by #Amine is mostly correct but some slight changes are required which I am giving here :
private void getDirection() {
String requestAPI;
try {
requestAPI = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_preference=less_driving&" +
"origin=" + pickuploc.latitude() + "," +
pickuploc.longitude() +
"&destination=" + droploc.latitude() + "," +
droploc.longitude() + "&" +
"key=" + getResources().getString(R.string.google_direction_apis);
/*If you get "PolylineOptions cannot be null" error and app crashes
while trying to draw polyline then try pasting your API
key in string directly like this "key=somekey". Though only for testing. */
mService.getPath(requestAPI)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, retrofit2.Response<String>
response) {
try {
new ParserTask().execute(response.body().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
UPD: I've found that there is something bad is happening to latitude and longitude field when I'm getting it from the database, for example it does not shows correctly using Toast.
I'm using a Firebase database in my project. It saves locations with additional information to Firebase database and I need to display markers corresponding to that locations on the map.
The writing database works without perfect.
However, reading does not work at all. I've followed this guide and defined the database as a field on my class, added instantiation in onCreate method and added ValueListener.
DatabaseReference databaseEvents;
//some code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
databaseEvents = FirebaseDatabase.getInstance().getReference("events");
}
//somecode
databaseEvents.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// events.clear();
Toast.makeText(MapsActivity.this, "LUL", Toast.LENGTH_SHORT).show();
for (DataSnapshot event : dataSnapshot.getChildren()) {
Event e = event.getValue(Event.class);
events.add(e);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//here I'm trying to display the markers.
When I'm trying to output the size of events it always prints 0 and so it does not print any marker on the map.
The full code is here:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, View.OnClickListener, GoogleMap.OnInfoWindowClickListener {
private static final int PLACE_PICKER_REQUEST = 1;
private GoogleMap mMap;
private Button addEventBtn;
private PlacePicker.IntentBuilder builder;
private Place place;
private EditText editEventName;
private Spinner typeOfEvent;
private LatLng coordOfNewMarker;
private String nameOfNewMarker;
private String typeOfNewMarker;
private ViewGroup infoWindow;
private TextView infoTitle;
private TextView infoSnippet;
private Button infoButton1, infoButton2;
private OnInfoWindowElemTouchListener infoButtonListener1, infoButtonListener2;
DatabaseReference databaseEvents;
#Override
public void onClick(View v) {
place = null;
switch (v.getId()) {
case R.id.AddEventButton:
callPlacePicker();
break;
}
}
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(this, "Info window clicked",
Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
databaseEvents = FirebaseDatabase.getInstance().getReference("events");
}
#Override
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;
addEventBtn = findViewById(R.id.AddEventButton);
final MapWrapperLayout mapWrapperLayout = findViewById(R.id.map_relative_layout);
mapWrapperLayout.init(mMap, getPixelsFromDp(MapsActivity.this, 39 + 20));
// We want to reuse the info window for all the markers,
// so let's create only one class member instance
this.infoWindow = (ViewGroup)getLayoutInflater().inflate(R.layout.custom_infowindow, null);
this.infoTitle = infoWindow.findViewById(R.id.nameTxt);
this.infoSnippet = infoWindow.findViewById(R.id.addressTxt);
this.infoButton1 = infoWindow.findViewById(R.id.btnOne);
this.infoButton2 = infoWindow.findViewById(R.id.btnTwo);
this.infoButtonListener1 = new OnInfoWindowElemTouchListener(infoButton1,
getResources().getDrawable(R.drawable.round_but_green_sel),
getResources().getDrawable(R.drawable.round_but_red_sel))
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
Toast.makeText(MapsActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
}
};
this.infoButton1.setOnTouchListener(infoButtonListener1);
this.infoButtonListener2 = new OnInfoWindowElemTouchListener(infoButton2,
getResources().getDrawable(R.drawable.round_but_green_sel),
getResources().getDrawable(R.drawable.round_but_red_sel))
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
Toast.makeText(MapsActivity.this, marker.getSnippet() + "'s button clicked!", Toast.LENGTH_SHORT).show();
}
};
this.infoButton2.setOnTouchListener(infoButtonListener2);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
infoTitle.setText(marker.getTitle());
infoSnippet.setText(marker.getSnippet());
infoButtonListener1.setMarker(marker);
infoButtonListener2.setMarker(marker);
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
final ArrayList<Event> events = new ArrayList<>();
databaseEvents.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// events.clear();
Toast.makeText(MapsActivity.this, "LUL", Toast.LENGTH_SHORT).show();
for (DataSnapshot event : dataSnapshot.getChildren()) {
Event e = event.getValue(Event.class);
events.add(e);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
/*
This code was being used for SQLite database which now is not being used at all.
ArrayList<Double> lat = new ArrayList<>();
ArrayList<Double> lng = new ArrayList<>();
ArrayList<String> name = new ArrayList<>();
ArrayList<String> type = new ArrayList<>();
String query = "SELECT * FROM "+ "locations";
Cursor cursor = locations.getWritableDatabase().rawQuery(query,null);
while(cursor.moveToNext()){
lat.add(cursor.getDouble(cursor.getColumnIndex("lat")));
lng.add(cursor.getDouble(cursor.getColumnIndex("lng")));
name.add(cursor.getString(cursor.getColumnIndex("name")));
type.add(cursor.getString(cursor.getColumnIndex("type")));
}*/
// It always print 0.
Toast.makeText(MapsActivity.this, ((Integer) events.size()).toString(), Toast.LENGTH_SHORT).show();
int sz = events.size();
for(int i = 0; i < sz; i++) {
mMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(events.get(i).getLatitude()), Double.parseDouble(events.get(i).getLongitude())))
.title(events.get(i).getName())
.snippet(events.get(i).getType()));
}
addEventBtn.setOnClickListener(this);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
place = PlacePicker.getPlace(this, data);
openDialog();
}
}
}
public void openDialog() {
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
editEventName = view.findViewById(R.id.editEventName);
typeOfEvent = view.findViewById(R.id.spinnerEventType);
final LocationsDB locations = new LocationsDB(this);
final StatsDB stats = new StatsDB(this);
try {
final String selected = typeOfEvent.getSelectedItem().toString();
}
catch (Exception e) {
Toast.makeText(this, "BAD", Toast.LENGTH_LONG);
}
builder.setView(view)
.setTitle("Create Event")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
coordOfNewMarker = place.getLatLng();
nameOfNewMarker = editEventName.getText().toString();
typeOfNewMarker = typeOfEvent.getSelectedItem().toString();
ContentValues event = new ContentValues();
Geocoder geocoder;
List<Address> addresses = new ArrayList<>();
geocoder = new Geocoder(getApplication(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(coordOfNewMarker.latitude,
coordOfNewMarker.longitude,
1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
String address = addresses.get(0).getAddressLine(0);
event.put("lat", coordOfNewMarker.latitude);
event.put("lng", coordOfNewMarker.longitude);
event.put("name", nameOfNewMarker);
event.put("type", typeOfNewMarker);
event.put("address", address);
locations.insert(event);
addEvent(coordOfNewMarker.longitude, coordOfNewMarker.latitude, typeOfNewMarker, nameOfNewMarker, address);
ContentValues created = new ContentValues();
created.put("type", "created");
created.put("number", stats.get() + 1);
stats.update(created);
mMap.addMarker(new MarkerOptions().position(place.getLatLng()).title(editEventName.getText().toString())
.snippet(typeOfEvent.getSelectedItem().toString()));
}
});
builder.show();
}
public void callPlacePicker() {
builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
}
catch (Exception e) {
e.printStackTrace();
}
}
public static int getPixelsFromDp(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dp * scale + 0.5f);
}
private void addEvent(Double lng, Double ltd, String type, String name, String address) {
String id = databaseEvents.push().getKey();
Event e = new Event(id, lng.toString(), ltd.toString(), type, name, address);
databaseEvents.child(id).setValue(e);
Toast.makeText(this, "Event added!", Toast.LENGTH_LONG).show();
}
}
I've tried in some way but the response is always null,
But the data will be sent I checked with toast and as expected
I also have used postman to check when the data sent in accordance with the key value then the results are appropriate.
this my code to send data
public class FragmentPetaniTerdekat extends Fragment {
Context context;
View view;
Dialog dialog;
RecyclerView recyclerView;
ArrayList<String> jenis = new ArrayList<>();
ArrayList<String> jarak = new ArrayList<>();
ArrayList<String> durasi = new ArrayList<>();
String my_location;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getContext();
dialog = new Dialog(context);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_fragment_petani, container, false);
location();
return view;
}
// get adddres name current location
private void location() {
dialog.showDialog("Pesan","memuat data...");
LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// get lat and lng
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
my_location = String.valueOf(lat+","+lng);
getApi(my_location);
Toast.makeText(context,String.valueOf(lat+","+lng),Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context,"lokasi tidak ditemukan",Toast.LENGTH_LONG).show();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
LocationManager mLocationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return ;
}
// check alternative get location
boolean GPS_ENABLE, NETWORK_ENABLE;
GPS_ENABLE = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
NETWORK_ENABLE = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (GPS_ENABLE){
Toast.makeText(getActivity(),"GPS state",Toast.LENGTH_LONG).show();
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 60 * 1 , 1, mLocationListener);
}else if(NETWORK_ENABLE){
Toast.makeText(getActivity(),"network state",Toast.LENGTH_LONG).show();
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1,mLocationListener);
}else{
Toast.makeText(getActivity(),"ganok seng kepilih cak",Toast.LENGTH_LONG).show();
showSettingsAlert();
}
}
// show alert setting if gps non aktif
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
getActivity().startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
public void initRecylerView(View v){
recyclerView = (RecyclerView)v.findViewById(R.id.recylerview_petani_terdekat);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
RecyclerView.Adapter adapter = new AdapterPetaniTerdekat(context,jenis,jarak,durasi);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void getApi(final String my_location){
Log.e("my_location", my_location);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL_PETANI_TERDEKAT, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
dialog.message(response.toString());
if (response != null) {
try {
JSONArray get_respone = response.getJSONArray("result_petani_terdekat");
for (int i=0; i<get_respone.length(); i++){
JSONObject result = get_respone.getJSONObject(i);
ModelPetaniTerdekat petaniTerdekat = new ModelPetaniTerdekat();
petaniTerdekat.setJenis(result.getString("jenis"));
JSONObject kriteria = result.getJSONObject("jarak");
for (int z=0; z<kriteria.length(); z++){
petaniTerdekat.setJarak(kriteria.getString("distance"));
petaniTerdekat.setDurasi(kriteria.getString("duration"));
}
jenis.add(petaniTerdekat.getJenis());
jarak.add(petaniTerdekat.getJarak());
durasi.add(petaniTerdekat.getDurasi());
dialog.closeDialog();
}
initRecylerView(view);
} catch (JSONException e) {
dialog.message("Error : "+e.toString());
e.printStackTrace();
}
}else{
dialog.message("Error : Tidak ada data !");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
dialog.message("Error : TimeoutError");
} else if (error instanceof AuthFailureError) {
dialog.message("Error : AuthFailureError");
} else if (error instanceof ServerError) {
dialog.message("Error : ServerError");
} else if (error instanceof NetworkError) {
dialog.message("Error : NetworkError");
} else if (error instanceof ParseError) {
error.printStackTrace();
dialog.message("Error : ParseError");
}
dialog.closeDialog();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> stringMap = new HashMap<>();
stringMap.put("lokasi_saya",my_location);
return stringMap;
}
};
AppSingleton.getInstance(context).addToRequestQueue(request);
request.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
}
this my web service
header('Content-Type: application/json');
include_once 'helper_api.php';
include_once '../crud.php';
if ($_SERVER['REQUEST_METHOD']=='POST') {
$origins = isset($_POST['lokasi_saya'])?$_POST['lokasi_saya']:"";
$crud = new Crud();
$sql = "SELECT tb_petani.id_petani, tb_petani.nama, tb_petani.no_telp, tb_petani.alamat, tb_jenis.nama_jenis
FROM tb_petani, tb_master_cabe, tb_jenis
WHERE tb_jenis.id_jenis = tb_master_cabe.id_jenis
AND tb_petani.id_petani = tb_master_cabe.id_petani
AND tb_petani.status ='2'";
$result = $crud->fetchData($sql);
$helper = new Helper_api();
$data_petani = array();
foreach ($result as $value) {
$destinatios = $value['alamat'];
$distance_duration = $helper->getDistanceDuration($origins, $destinatios);
$data_petani[] = array(
"nama"=>$value['nama'],
"no_telp"=>$value['no_telp'],
"alamat"=>$value['alamat'],
"jenis"=>$value['nama_jenis'],
"jarak"=>$distance_duration
);
}
// sort ascending array multidimensi (distance)
usort($data_petani, function($a, $b) {
return $a['jarak']['distance'] - $b['jarak']['distance'];
});
echo json_encode(array("result_petani_terdekat"=>$data_petani));
}
try with sending data in key-value pair, try this code :
HashMap<String, String> inputs = new HashMap<String, String>();
inputs.put("your key1", "value");
inputs.put("your key2", "value2");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
URL_PETANI_TERDEKAT, new JSONObject(inputs),
new com.android.volley.Response.Listener<JSONObject>() {
......
}
Try to add this code with getparams()
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
problem solved
I replaced the objectRequest into the stringRequest parameter successfully sent
Thank you very much guys
I am trying to handle events apart from the onCamerachange Listener such as knowing the event when the camera is dragged and released. For that I have taken help of a custom touch fragment and touch wrapper to manage the touch events but without success.
Here is my main activity code :
public class PickupActivity extends LocationUtils implements OnMapReadyCallback, AddressSearchAdapter.ClickListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LatLng center;
private TextView pickupMarker;
private LinearLayout markerLayout, addressBox, confirmPickupLayout;
private EditText address, pincodeText, landmarkText;
private ImageView currentLocationButton;
private LatLng latLng, latLng1;
private JSONArray addressComponents, typesArray;
String formattedAddress;
String currentLatitude, currentLongitude;
private Toolbar toolbar;
private SharedPreferenceClass preferenceClass;
private String pincode, gPlaceId, city, country, state, premise, route, enteredText, pickupLat, pickupLong, currentGplaceId;
private AddressSearchAdapter mAdapter;
private RecyclerView mRecyclerView;
private ArrayList<com.packr.classes.Address> addressArrayList = new ArrayList<>();
private JSONObject locationObject, geometryObject;
private com.packr.classes.Address mAddress;
private int pickupToastVisible = 0;
private Boolean pickupLocationSet = false, isAddressTextEmpty = false;
private Button confirmPickupButton;
private Double a, b, x, y;
/**
* Represents a geographical location.
*/
protected Location mLastLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pickup);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
initialize();
onClick();
onSearchTextChanged();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setVisibility(View.GONE);
mRecyclerView.setLayoutManager(new MyLinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
mAdapter = new AddressSearchAdapter(getApplicationContext(), this);
mAdapter.setClickListener(this);
mRecyclerView.setAdapter(mAdapter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Set Pickup Location");
setSupportActionBar(toolbar);
}
/**
* function to load map. If map is not created it will create it for you
* */
#Override
public void onResume() {
super.onResume();
}
public void initialize() {
confirmPickupLayout = (LinearLayout) findViewById(R.id.confirmPickupLayout);
preferenceClass = new SharedPreferenceClass(getApplicationContext());
pickupMarker = (TextView) findViewById(R.id.locationMarkertext);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
address = (EditText) findViewById(R.id.addressText);
currentLocationButton = (ImageView) findViewById(R.id.current_location);
addressBox = (LinearLayout) findViewById(R.id.addressBox);
pincodeText = (EditText) findViewById(R.id.pincodeText);
landmarkText = (EditText) findViewById(R.id.landmarkText);
confirmPickupButton = (Button) findViewById(R.id.confirmPickup);
}
public void onClick() {
}
public void onSearchTextChanged() {
address.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() == 0 || s == "") {
isAddressTextEmpty = true;
if (mRecyclerView.getVisibility() == View.VISIBLE) {
mRecyclerView.setVisibility(View.GONE);
}
}
if (s.length() < 16) {
mRecyclerView.setVisibility(View.VISIBLE);
enteredText = s.toString().replace(" ", "");
if (isAddressTextEmpty) {
sendAutocompleteJsonRequest();
}
}
final List<com.packr.classes.Address> filteredModelList = filter(addressArrayList, s.toString());
mAdapter.animateTo(filteredModelList);
mRecyclerView.scrollToPosition(0);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onMapReady(GoogleMap map) {
TouchableMapFragment mFragment;
mFragment = new TouchableMapFragment();
new MapStateListener(map,mFragment,this){
#Override
public void onMapTouched() {
// Map touched
L.m("touched");
}
#Override
public void onMapReleased() {
// Map released
L.m("released");
}
#Override
public void onMapUnsettled() {
// Map unsettled
L.m("unSettled");
}
#Override
public void onMapSettled() {
// Map settled
L.m("settled");
}
};
mMap = map;
map.setMyLocationEnabled(false);
currentLatitude = preferenceClass.getCurrentLatitude();
currentLongitude = preferenceClass.getCurrentLongitude();
a = Double.parseDouble(currentLatitude);
b = Double.parseDouble(currentLongitude);
latLng = new LatLng(Double.parseDouble(currentLatitude), Double.parseDouble(currentLongitude));
map.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory
.fromResource(R.drawable.current_location_marker)));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(15f).tilt(0).bearing(0).build();
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.moveCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
address.setText(preferenceClass.getPickupAddress());
pincodeText.setText(preferenceClass.getPickupPincode());
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
if (confirmPickupLayout.getVisibility() == View.VISIBLE) {
confirmPickupLayout.setVisibility(View.GONE);
slideOutTowardsBottom();
}
center = mMap.getCameraPosition().target;
currentLatitude = String.valueOf(center.latitude);
currentLongitude = String.valueOf(center.longitude);
latLng1 = new LatLng(center.latitude, center.longitude);
Log.e("Coordinates", String.valueOf(center.latitude) + "," + String.valueOf(center.longitude) + latLng1);
pickupMarker.setText(" Set your Location ");
if (!pickupLocationSet) {
float[] distances = new float[1];
Location.distanceBetween(center.latitude, center.longitude, a, b, distances);
System.out.println("Distance: " + distances[0]);
if (distances[0] > 1000.0) {
sendJsonRequest();
L.m("called");
a = center.latitude;
b = center.longitude;
}
}
}
});
}
public void sendJsonRequest() {
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getRequestUrl(), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
//console test
parseJsonResponse(jsonObject);
if (formattedAddress == null) {
address.setText("Obtaining Address");
} else {
address.setText(formattedAddress);
}
Log.e("error", jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
} else if (volleyError instanceof AuthFailureError) {
} else if (volleyError instanceof ServerError) {
} else if (volleyError instanceof NetworkError) {
} else if (volleyError instanceof ParseError) {
}
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
1000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
requestQueue.add(jsonObjectRequest);
}
public String getRequestUrl() {
return KEY_GEOCODE_URL +
currentLatitude + KEY_COMMA + currentLongitude +
KEY_SENSOR;
}
public void parseJsonResponse(JSONObject response) {
if (response != null && response.length() > 0) {
try {
JSONArray resultArray = response.getJSONArray(KEY_RESULTS);
if (resultArray.length() > 0) {
for (int i = 0; i < resultArray.length(); i++) {
JSONObject resultListObject = resultArray.getJSONObject(0);
formattedAddress = resultListObject.getString(KEY_FORMATTED_ADDRESS);
addressComponents = resultListObject.getJSONArray(KEY_ADDRESS_COMPONENTS);
gPlaceId = resultListObject.getString(KEY_PLACE_ID);
preferenceClass.savePickupGplaceId(gPlaceId);
}
if (addressComponents.length() > 0) {
for (int j = 0; j < addressComponents.length(); j++) {
JSONObject addressComponentsObject = addressComponents.getJSONObject(j);
typesArray = addressComponentsObject.getJSONArray(KEY_TYPES);
if ((typesArray.getString(0)).contentEquals(KEY_POSTAL_CODE)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
pincode = addressComponentsObject.getString(KEY_LONG_NAME);
pincodeText.setText(pincode);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public String getAutocompleteRequestUrl() {
return KEY_AUTOCOMPLETE_API.concat(enteredText);
}
public void sendAutocompleteJsonRequest() {
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, getAutocompleteRequestUrl(), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
parseJSONResponse(jsonObject);
//Calling the Snackbar
Log.e("response", jsonObject.toString());
mAdapter.setAddressArrayList(addressArrayList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
} else if (volleyError instanceof AuthFailureError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
} else if (volleyError instanceof ServerError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
} else if (volleyError instanceof NetworkError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
} else if (volleyError instanceof ParseError) {
L.T(getApplicationContext(), "Something is wrong with the internet connectivity. Please try again");
//TODO
}
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
1000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
}
private void parseJSONResponse(JSONObject response) {
if (response != null && response.length() > 0) {
try {
JSONArray resultArray = response.getJSONArray(KEY_RESULTS);
if (resultArray.length() > 0) {
for (int i = 0; i < resultArray.length(); i++) {
JSONObject resultListObject = resultArray.getJSONObject(i);
formattedAddress = resultListObject.getString(KEY_FORMATTED_ADDRESS);
addressComponents = resultListObject.getJSONArray(KEY_ADDRESS_COMPONENTS);
gPlaceId = resultListObject.getString(KEY_PLACE_ID);
if (resultListObject.has(KEY_LOCATION) && !(resultListObject.isNull(KEY_LOCATION))) {
locationObject = resultListObject.getJSONObject(KEY_LOCATION);
if (locationObject.has(KEY_LATITUDE) && !(locationObject.isNull(KEY_LATITUDE))) {
currentLatitude = locationObject.getString(KEY_LATITUDE);
}
if (locationObject.has(KEY_LONGITUDE) && !(locationObject.isNull(KEY_LONGITUDE))) {
currentLongitude = locationObject.getString(KEY_LONGITUDE);
}
}
if ((resultListObject.has(KEY_GEOMETRY)) && !(resultListObject.isNull(KEY_GEOMETRY))) {
geometryObject = resultListObject.getJSONObject(KEY_GEOMETRY);
if (geometryObject.has(KEY_LOCATION) && !(geometryObject.isNull(KEY_LOCATION))) {
locationObject = geometryObject.getJSONObject(KEY_LOCATION);
if (locationObject.has(KEY_LATITUDE) && !(locationObject.isNull(KEY_LATITUDE))) {
currentLatitude = locationObject.getString(KEY_LATITUDE);
}
if (locationObject.has(KEY_LONGITUDE) && !(locationObject.isNull(KEY_LONGITUDE))) {
currentLongitude = locationObject.getString(KEY_LONGITUDE);
}
}
}
if (addressComponents.length() > 0) {
for (int j = 0; j < addressComponents.length(); j++) {
JSONObject addressComponentsObject = addressComponents.getJSONObject(j);
typesArray = addressComponentsObject.getJSONArray(KEY_TYPES);
if ((typesArray.getString(0)).contentEquals(KEY_CITY)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
city = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_COUNTRY)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
country = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_STATE)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
state = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_POSTAL_CODE)) {
if (!addressComponentsObject.isNull(KEY_LONG_NAME))
pincode = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_PREMISE)) {
premise = addressComponentsObject.getString(KEY_LONG_NAME);
} else if ((typesArray.getString(0)).contentEquals(KEY_ROUTE)) {
route = addressComponentsObject.getString(KEY_LONG_NAME);
}
}
}
if (country.contentEquals("India") && city.contentEquals("Kolkata")) {
mAddress = new com.packr.classes.Address();
mAddress.setFormattedAddress(formattedAddress);
mAddress.setCity(city);
mAddress.setCountry(country);
mAddress.setPincode(pincode);
mAddress.setState(state);
mAddress.setStreet(premise);
mAddress.setRoute(route);
mAddress.setLatitude(currentLatitude);
mAddress.setLongitude(currentLongitude);
mAddress.setGplaceId(gPlaceId);
addressArrayList.add(mAddress);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private List<com.packr.classes.Address> filter(List<com.packr.classes.Address> models, String query) {
query = query.toLowerCase();
final List<com.packr.classes.Address> filteredModelList = new ArrayList<>();
for (com.packr.classes.Address model : models) {
final String text = model.getFormattedAddress().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
public void slideInFromBottom() {
Animation tvAnim = AnimationUtils.loadAnimation(this, R.anim.abc_slide_in_bottom);
confirmPickupLayout.startAnimation(tvAnim);
}
public void slideOutTowardsBottom() {
Animation tvAnim = AnimationUtils.loadAnimation(this, R.anim.abc_slide_out_bottom);
confirmPickupLayout.startAnimation(tvAnim);
}
// to check whether location services are enable or not
public static boolean isLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
} else {
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
#Override
public void itemClicked(View view, int position) {
hideKeyboard();
confirmPickupLayout.setVisibility(View.VISIBLE);
slideInFromBottom();
mRecyclerView.setVisibility(View.GONE);
pickupLat = addressArrayList.get(position).getLatitude();
pickupLong = addressArrayList.get(position).getLongitude();
preferenceClass.savePickupLatitude(currentLatitude);
preferenceClass.savePickupLongitude(currentLongitude);
String pincode = addressArrayList.get(position).getPincode();
currentGplaceId = addressArrayList.get(position).getGplaceId();
preferenceClass.savePickupGplaceId(currentGplaceId);
latLng = new LatLng(Double.parseDouble(pickupLat), Double.parseDouble(pickupLong));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(15f).tilt(0).bearing(0).build();
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
address.setText(formattedAddress);
if (pincode != null) {
pincodeText.setText(pincode);
}
}
public Boolean validationCheck() {
if (address.getText().length() == 0) {
L.t(getApplicationContext(), "Please provide a pickup address");
} else if (pincodeText.getText().length() != 6) {
L.t(getApplicationContext(), "Pincode must contain 6 digits");
} else if (landmarkText.getText().length() == 0) {
L.t(getApplicationContext(), "Please provide a landmark");
} else return true;
return false;
}
private void hideKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
Here is the code for the custom Touch fragement. I have extended MapSupportFragment
public class TouchableMapFragment extends MapFragment {
private View mOriginalContentView;
private TouchableWrapper mTouchView;
public void setTouchListener(TouchableWrapper.OnTouchListener onTouchListener) {
mTouchView.setTouchListener(onTouchListener);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
L.m("called");
mOriginalContentView = super.onCreateView(inflater, parent,
savedInstanceState);
mTouchView = new TouchableWrapper(getActivity());
mTouchView.addView(mOriginalContentView);
return mTouchView;
}
#Override
public View getView() {
return mOriginalContentView;
}
}
Here is the code for the touchWrapper
public class TouchableWrapper extends FrameLayout {
public TouchableWrapper(Context context) {
super(context);
}
public void setTouchListener(OnTouchListener onTouchListener) {
this.onTouchListener = onTouchListener;
}
private OnTouchListener onTouchListener;
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
onTouchListener.onTouch();
break;
case MotionEvent.ACTION_UP:
onTouchListener.onRelease();
break;
}
return super.dispatchTouchEvent(event);
}
public interface OnTouchListener {
void onTouch();
void onRelease();
}
}
Please help.