how to start activity when click on marker with json and clustering
my map is already clustering but i cant start to new activity when click on marker without title
this is my code
package tmg.tower;
/**
* Created by DIMAS on 25/06/2015.
*/
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.maps.android.clustering.ClusterManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends Activity implements GoogleMap.OnMarkerClickListener, View.OnClickListener {
private JSONParser json;
private LatLng myLocation;
ArrayList<HashMap<String, String>> dataMap = new ArrayList<HashMap<String, String>>();
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
Server serv = new Server();
String conn = serv.connection();
String url = conn + "********";
JSONArray str_json = null;
static final int showerror = 1;
public static final String SP = "shareAt";
SharedPreferences shareAt;
public static final String KEY_LAT_TUJUAN = "lat_tujuan";
public static final String KEY_LNG_TUJUAN = "lng_tujuan";
static final LatLng AWAL = new LatLng(3.584695, 98.675079);
Button mBtnFind;
EditText etPlace;
Button searchlist;
private ClusterManager<MyItem> mClusterManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LatLng myPosition;
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("GPS Disabled, Buka Setting dan Aktifkan GPS?")
.setCancelable(false)
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
finish();
}
})
.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
finish();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
Toast.makeText(getApplicationContext(), "GPS Enabled", Toast.LENGTH_LONG).show();
}
if (cek_status(this)) {
Server serv = new Server();
conn = serv.connection();
new getListInfo().execute();
} else {
showDialog(showerror);
}
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment
= (MapFragment) myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
myMap.getUiSettings().setZoomControlsEnabled(true);
myMap.getUiSettings().setCompassEnabled(true);
myMap.getUiSettings().setMyLocationButtonEnabled(true);
myMap.getUiSettings().setAllGesturesEnabled(true);
myMap.setTrafficEnabled(true);
myMap.setOnMarkerClickListener(this);
myMap.moveCamera(CameraUpdateFactory.newLatLngZoom(AWAL, 15));
myMap.setBuildingsEnabled(true);
myMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
mBtnFind = (Button) findViewById(R.id.btn_show);
etPlace = (EditText) findViewById(R.id.et_place);
searchlist = (Button) findViewById(R.id.searchlist);
searchlist.setOnClickListener(this);
mBtnFind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Getting the place entered
String location = etPlace.getText().toString();
if(location==null || location.equals("")){
Toast.makeText(getBaseContext(), "No Place is entered", Toast.LENGTH_SHORT).show();
return;
}
String url = "https://**********";
try {
// encoding special characters like space in the user input place
location = URLEncoder.encode(location, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String siteid = "Site_ID=" + location;
String sensor = "sensor=false";
// url , from where the geocoding data is fetched
url = url + siteid + "&" + sensor;
// Instantiating DownloadTask to get places from Google Geocoding service
// in a non-ui thread
DownloadTask downloadTask = new DownloadTask();
// Start downloading the geocoding places
downloadTask.execute(url);
}
});
}
public void onClick (View v){
Intent i = new Intent(MainActivity.this,Search.class);
startActivity(i);
}
public boolean cek_status(Context cek) {
ConnectivityManager cm = (ConnectivityManager) cek.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
} else {
return false;
}
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case showerror:
AlertDialog.Builder errorDialog = new AlertDialog.Builder(this);
errorDialog.setTitle("Error Connection");
errorDialog.setMessage("Please check your internet connection");
errorDialog.setNeutralButton("exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
Intent exit = new Intent(Intent.ACTION_MAIN);
exit.addCategory(Intent.CATEGORY_HOME);
exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainActivity.this.finish();
startActivity(exit);
}
});
AlertDialog errorAlert = errorDialog.create();
return errorAlert;
default:
break;
}
return dialog;
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode != ConnectionResult.SUCCESS) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
#SuppressLint("LongLogTag")
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Places from Geocoding webservice */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result){
// Instantiating ParserTask which parses the json data from Geocoding webservice
// in a non-ui thread
ParserTask parserTask = new ParserTask();
// Start parsing the places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
class getListInfo extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("Loading server...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
JSONObject json = jParser.AmbilJson(url);
try {
str_json = json.getJSONArray("tower");
for (int i = 0; i < str_json.length(); i++) {
JSONObject ar = str_json.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("Site ID", ar.getString("Site ID"));
map.put("Site Name", ar.getString("Site Name"));
map.put("Address", ar.getString("Address"));
map.put("Lattitude", ar.getString("Lattitude"));
map.put("Longitude", ar.getString("Longitude"));
dataMap.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
mClusterManager = new ClusterManager<MyItem>(getApplicationContext(), myMap);
myMap.setOnCameraChangeListener(mClusterManager);
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
for (int i = 0; i < dataMap.size(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
List<MyItem> items = new ArrayList<MyItem>();
map = dataMap.get(i);
mClusterManager.addItem(new MyItem(Double.parseDouble(map.get("Lattitude")), Double.parseDouble(map.get("Longitude"))));
}
}
});
}
}
class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
GeocodeJSONParser parser = new GeocodeJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a an ArrayList */
places = parser.parse(jObject);
}catch(Exception e){
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String,String>> list){
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("Lattitude"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("Longitude"));
// Getting name
String name = hmPlace.get("Site ID");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Locate the first location
if(i==0)
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
TextView tvLocInfo;
#Override
public boolean onMarkerClick(Marker marker) {
myLocation = new LatLng(myMap.getMyLocation().getLatitude(), myMap.getMyLocation().getLongitude());
if (myLocation != null) {
Bundle bundle = new Bundle();
bundle.putDouble(KEY_LAT_TUJUAN, marker.getPosition().latitude);
bundle.putDouble(KEY_LNG_TUJUAN, marker.getPosition().longitude);
shareAt = getBaseContext().getSharedPreferences(SP, 0);
SharedPreferences.Editor editor = shareAt.edit();
String replace_string_first = marker.getTitle().replace(" ", "_");
editor.putString("Site ID", replace_string_first);
editor.putString("Lattitude", replace_string_first);
editor.putString("Longitude", replace_string_first);
editor.commit();
Intent intent = new Intent(MainActivity.this, Main.class);
intent.putExtras(bundle);
intent.putExtra("Site ID", replace_string_first);
intent.putExtra("Lattitude", replace_string_first);
intent.putExtra("Longitude", replace_string_first);
startActivity(intent);
}
return false;
}
}
how to get intent json object without marker.getTitle ?
thanks for help
Related
MyLocation.Java
package com.example.mycoordinate;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.Polyline;
import com.google.maps.android.SphericalUtil;
public class MyLocation extends AppCompatActivity implements LocationListener {
private GoogleMap googleMap;
private SupportMapFragment supportMapFragment;
private MarkerOptions place1, place2;
//getLocation()
LocationManager locationManager;
String locationText = "";
String locationLatitude = "";
String locationLongitude = "";
private Handler mHandler ;
private int mInterval = 3000; // after the coordinate is found, refresh every 3 seconds.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps_offline);
supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
//Alert Dialog
AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(
MyLocation.this);
// Setting Dialog Title
alertDialog2.setTitle("Notification");
// Setting Dialog Message
String string1 = "Give it 10-15 seconds for your coordinates to update. Keep moving around and you will see coordinates update.";
alertDialog2.setMessage(string1);
// Setting Icon to Dialog
alertDialog2.setIcon(R.drawable.ic_launcher_background);
// Setting Positive "Yes" Btn
// alertDialog2.setPositiveButton("Continue",
// new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
//
// }
// });
// Showing Alert Dialog
alertDialog2.show();
Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
public void run() {
mHandler = new Handler();
startRepeatingTask();
}
}, 1000); //5 seconds
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
}
#Override
public void onDestroy() {
super.onDestroy();
stopRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
final EditText yourlat = (EditText) findViewById(R.id.yourLat);
final EditText yourlong = (EditText) findViewById(R.id.yourLong);
try {
getLocation(); //this function can change value of mInterval.
if (locationText.toString() == "") {
Toast.makeText(getApplicationContext(), "Locating us...", Toast.LENGTH_LONG).show();
} else {
yourlat.setText(locationLatitude.toString());
yourlong.setText(locationLongitude.toString());
}
} finally {
mHandler.postDelayed(mStatusChecker, mInterval);
}
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
void getLocation() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 5, (LocationListener) this);
}
catch(SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
locationText = location.getLatitude() + "," + location.getLongitude();
locationLatitude = location.getLatitude() + "";
locationLongitude = location.getLongitude() + "";
final LatLng home = new LatLng(1.363451, 103.834337); //HOME
final LatLng current = new LatLng(location.getLatitude(), location.getLongitude()); //current position
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
// double zoomLevel = googleMap.getCameraPosition().zoom;
// if (zoomLevel < 8) {
// zoomLevel = 18.0;
// }
// googleMap.clear();
//googleMap.addMarker(new MarkerOptions().position(current_position).title("Current Location"));
//googleMap.moveCamera(CameraUpdateFactory.newLatLng(current_position) );
//googleMap.animateCamera( CameraUpdateFactory.zoomTo( (float) zoomLevel) );
//googleMap.addMarker(new MarkerOptions().position(home).title("Home"));
//googleMap.moveCamera(CameraUpdateFactory.newLatLng(place1.getPosition()) );
place1 = new MarkerOptions().position(current).title("Current");
place2 = new MarkerOptions().position(home).title("Home");
googleMap.addMarker(place1);
googleMap.addMarker(place2);
//Route between two points
new FetchURL(MyLocation.this).execute(getUrl(place1.getPosition(), place2.getPosition(), "driving"), "driving" );
//distance between two points in a Straight Line
Double distance = SphericalUtil.computeDistanceBetween(place1.getPosition(), place2.getPosition());
CameraPosition googlePlex = CameraPosition.builder()
.target(place1.getPosition())
.zoom(16)
.bearing(0)
//.tilt(45)
.build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 10000, null);
Log.d("Location", "Distance: " + distance );
}
});
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MyLocation.this, "Please Enable GPS", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
private String getUrl(LatLng origin, LatLng dest, String directionMode) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Mode
String mode = "mode=" + directionMode;
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + mode;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters + "&key=" + getString(R.string.google_maps_key);
Log.d("TEST", "getUrl: " + url);
return url;
}
}
FetchURL.java
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class FetchURL extends AsyncTask<String, Void, String> {
Context mContext;
String directionMode = "driving";
public FetchURL(Context mContext) {
this.mContext = mContext;
}
#Override
protected String doInBackground(String... strings) {
// For storing data from web service
String data = "";
directionMode = strings[1];
try {
// Fetching the data from web service
data = downloadUrl(strings[0]);
Log.d("mylog", "Background task data " + data.toString());
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
PointsParser parserTask = new PointsParser(mContext, directionMode);
// Invokes the thread for parsing the JSON data
parserTask.execute(s);
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
Log.d("mylog", "Downloaded URL: " + data.toString());
br.close();
} catch (Exception e) {
Log.d("mylog", "Exception downloading URL: " + e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
}
PointsParser.java
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class PointsParser extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
TaskLoadedCallback taskCallback;
String directionMode = "driving";
public PointsParser(Context mContext, String directionMode) {
this.taskCallback = (TaskLoadedCallback) mContext; <---- this is the error
this.directionMode = directionMode;
}
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
Log.d("mylog", jsonData[0].toString());
DataParser parser = new DataParser();
Log.d("mylog", parser.toString());
// Starts parsing data
routes = parser.parse(jObject);
Log.d("mylog", "Executing routes");
Log.d("mylog", routes.toString());
} catch (Exception e) {
Log.d("mylog", e.toString());
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
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);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
if (directionMode.equalsIgnoreCase("walking")) {
lineOptions.width(10);
lineOptions.color(Color.MAGENTA);
} else {
lineOptions.width(20);
lineOptions.color(Color.RED);
}
Log.d("mylog", "onPostExecute lineoptions decoded");
}
// Drawing polyline in the Google Map for the i-th route
if (lineOptions != null) {
//mMap.addPolyline(lineOptions);
taskCallback.onTaskDone(lineOptions);
} else {
Log.d("mylog", "without Polylines drawn");
}
taskCallback.onTaskDone();
}
}
TaskLoadedCallback.java
public interface TaskLoadedCallback {
void onTaskDone(Object... values);
}
It has been almost a week trying to understand and trying to fix this the error Below.
2019-08-12 14:29:01.822 14672-14672/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2019-08-12 14:29:01.824 14672-14672/? E/Zygote: accessInfo : 1
2019-08-12 14:29:01.866 14672-14680/? E/le.mycoordinat: Unable to peek into adb socket due to error. Closing socket.: Connection reset by peer
2019-08-12 14:29:03.831 14672-14672/com.example.mycoordinate E/ViewRootImpl#c1f726b[MyLocation]: mStopped=false mHasWindowFocus=true mPausedForTransition=false
2019-08-12 14:29:03.859 14672-14672/com.example.mycoordinate E/ViewRootImpl: sendUserActionEvent() returned.
2019-08-12 14:29:07.662 14672-14672/com.example.mycoordinate E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mycoordinate, PID: 14672
java.lang.ClassCastException: com.example.mycoordinate.MyLocation cannot be cast to com.example.mycoordinate.TaskLoadedCallback
at com.example.mycoordinate.PointsParser.<init>(PointsParser.java:20)
at com.example.mycoordinate.FetchURL.onPostExecute(FetchURL.java:44)
at com.example.mycoordinate.FetchURL.onPostExecute(FetchURL.java:18)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.access$600(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:6986)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
Any kindhearted individual who can help me with this? It has been almost a week since i started this journey. I already passed (MyLocation.this - as reference to the activity) but it still doesnt work... do note my Google API is working fine.
Please help.
This is because you are passing MyLocation to PointsParser and try to cast it to TaskLoadedCallback in this.taskCallback = (TaskLoadedCallback) mContext;, add TaskLoadedCallback to implements in MyLocation
public class MyLocation extends AppCompatActivity implements LocationListener, TaskLoadedCallback {
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
in my applicationi want to show my locations from database and i find code do that but i get this error so please help me !!
'here is my MainnActivity '
package com.ry.rhcomptence.accessiblemaroc;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
public class MainnActivity extends FragmentActivity implements OnMapReadyCallback {
GoogleMap mGoogleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainn);
// Getting reference to SupportMapFragment
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
// Creating GoogleMap from SupportMapFragment
//mGoogleMap = fragment.getMap();
fragment.getMapAsync(this);
// Setting OnClickEvent listener for the GoogleMap
/**mGoogleMap.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng latlng) {
addMarker(latlng);
sendToServer(latlng);
}
});*/
// Starting locations retrieve task
new RetrieveTask().execute();
}
// Adding marker on the GoogleMaps
private void addMarker(LatLng latlng) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latlng);
markerOptions.title(latlng.latitude + "," + latlng.longitude);
mGoogleMap.addMarker(markerOptions);
}
// Invoking background thread to store the touched location in Remove MySQL server
private void sendToServer(LatLng latlng) {
new SaveTask().execute(latlng);
}
#Override
public void onMapReady(GoogleMap googleMap) {
// Enabling MyLocation button for the Google Map
/**if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
mGoogleMap.setMyLocationEnabled(true);*/
}
// Background thread to save the location in remove MySQL server
private class SaveTask extends AsyncTask<LatLng, Void, Void> {
#Override
protected Void doInBackground(LatLng... params) {
String lat = Double.toString(params[0].latitude);
String lng = Double.toString(params[0].longitude);
String strUrl = "https://accessiblemaroc.000webhostapp.com/save.php";
URL url = null;
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
connection.getOutputStream());
outputStreamWriter.write("lat=" + lat + "&lng="+lng);
outputStreamWriter.flush();
outputStreamWriter.close();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new
InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( (line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
// Background task to retrieve locations from remote mysql server
private class RetrieveTask extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
String strUrl = "https://accessiblemaroc.000webhostapp.com/retrieve.php";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while( (line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
// Background thread to parse the JSON data retrieved from MySQL server
private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>>{
#Override
protected List<HashMap<String,String>> doInBackground(String... params) {
MarkerJSONParser markerParser = new MarkerJSONParser();
JSONObject json = null;
try {
json = new JSONObject(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
List<HashMap<String, String>> markersList = markerParser.parse(json);
return markersList;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
for(int i=0; i<result.size();i++){
HashMap<String, String> marker = result.get(i);
LatLng latlng = new LatLng(Double.parseDouble(marker.get("lat")), Double.parseDouble(marker.get("lng")));
addMarker(latlng);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
'here where is the problem MarkerJSONParser.JAVA :'
package com.ry.rhcomptence.accessiblemaroc;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MarkerJSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jMarkers =null;
try {
/** Retrieves all the elements in the 'markers' array */
jMarkers = jObject.getJSONArray("markers");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getMarkers with the array of json object
* where each json object represent a marker
*/
return getMarkers(jMarkers);
}
private List<HashMap<String, String>> getMarkers(JSONArray jMarkers){
int markersCount = jMarkers.length();
List<HashMap<String, String>> markersList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> marker = null;
/** Taking each marker, parses and adds to list object */
for(int i=0; i<markersCount;i++){
try {
/** Call getMarker with marker JSON object to parse the marker */
marker = getMarker((JSONObject)jMarkers.get(i));
markersList.add(marker);
}catch (JSONException e){
e.printStackTrace();
}
}
return markersList;
}
/** Parsing the Marker JSON object */
private HashMap<String, String> getMarker(JSONObject jMarker){
HashMap<String, String> marker = new HashMap<String, String>();
String lat = "-NA-";
String lng ="-NA-";
try {
// Extracting latitude, if available
if(!jMarker.isNull("lat")){
lat = jMarker.getString("lat");
}
// Extracting longitude, if available
if(!jMarker.isNull("lng")){
lng = jMarker.getString("lng");
}
marker.put("lat", lat);
marker.put("lng", lng);
} catch (JSONException e) {
e.printStackTrace();
}
return marker;
}
}
'and finally this is the ERROR'
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.ry.rhcomptence.accessiblemaroc.MarkerJSONParser.parse(MarkerJSONParser.java:19)
at com.ry.rhcomptence.accessiblemaroc.MainnActivity$ParserTask.doInBackground(MainnActivity.java:191)
at com.ry.rhcomptence.accessiblemaroc.MainnActivity$ParserTask.doInBackground(MainnActivity.java:181)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
You are not trying to get data in your ParserTask
private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>>{
#Override
protected List<HashMap<String,String>> doInBackground(String... params) {
MarkerJSONParser markerParser = new MarkerJSONParser();
JSONObject json = null;
try {
json = new JSONObject(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
List<HashMap<String, String>> markersList = markerParser.parse(json);
return markersList;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
for(int i=0; i<result.size();i++){
HashMap<String, String> marker = result.get(i);
LatLng latlng = new LatLng(Double.parseDouble(marker.get("lat")), Double.parseDouble(marker.get("lng")));
addMarker(latlng);
}
}
}
You mentioned that this is a:
//Background thread to parse the JSON data retrieved from MySQL server
But you are not retrieving data from your MySQL Server which in return would give you nothing. And when you pass that nothing to your MarkerJSONParser and try to parse nothing. It would result to the NullPointerException.
I want to Delete a record from the database when i click on the Buttton.
The Button i set in the listView.
I want to perfrom this on ListView Here i tried following way but its not working..
Here My API
<?php
include("connection.php");
$tbl = "abc";
$idToDelete = $_GET["id"];
$delete_row = mysql_query("DELETE FROM $tbl WHERE o_id=".$idToDelete);
$response["delete"] = array();
$response["success"]=1;
// push single product into final response array
echo json_encode($response);
?>
ListviewAdapter.java
package com.example.sachin.alertbox;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ActionMenuView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button add;
Spinner spinner;
ListView listview;
LinearLayout linearlayout;
JSONObject jsonobject;
private static String url_addevent = "http ://10.0.2.2/portal/order_product.php";
public static String url_visitor= "http://10.0.2.2/portal/fetchorder_of_user.php";
JSONParser jParser = new JSONParser();
JSONArray ownerObj;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<String> delivery_fetch = new ArrayList<String>();
ListViewAdapterorder listadapter;
EditText qty;
LinearLayout layout;
ActionMenuView.LayoutParams params;
LinearLayout mainLayout;
PopupWindow popUp;
final Context context = this;
ArrayAdapter<String> adapter;
Button Delete;
ArrayList<String> listItems = new ArrayList<>();
String stringqty,stringspinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.clickme);
popUp = new PopupWindow(this);
layout = new LinearLayout(this);
mainLayout = new LinearLayout(this);
listview = (ListView)findViewById(R.id.listview);
Delete=(Button)findViewById(R.id.delete);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
spinner=(Spinner)promptsView.findViewById(R.id.spinner);
adapter = new ArrayAdapter<String>(getApplication(), R.layout.spinner_layout, R.id.txt, listItems);
spinner.setAdapter(adapter);
spinner.setSelection(0);
qty=(EditText)promptsView.findViewById(R.id.qty);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
// edit text
stringqty=qty.getText().toString();
stringspinner=spinner.getSelectedItem().toString();
addvisitor();
new fetchorder().execute();
Toast.makeText(getApplicationContext(), "qty : " + stringqty +stringspinner, Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
private void addvisitor() {
service(stringqty,stringspinner);
}
private void service(String qty,String sp) {
class AddVisitclass extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
//#Override
protected void onPreExecute() {
// Create a progressdialog
super.onPreExecute();
//loading = ProgressDialog.show(getApplicationContext(), "Please Wait...!!!", null, true, true);
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> param = new HashMap<String, String>();
param.put("quantity", params[0]);
param.put("model", params[1]);
String result = ruc.sendPostRequest(url_addevent, param);
Log.d("Result", result);
Log.d("Data", param.toString());
return result;
}
//#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//loading.dismiss();
Toast.makeText(getApplicationContext(), "Service Added Successfully...!!!", Toast.LENGTH_LONG).show();
/* Intent i1 = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(i1);*/
}
}
AddVisitclass regi = new AddVisitclass();
regi.execute(qty,sp);
}
ArrayList<String> o_aid= new ArrayList<String>();
ArrayList<String> o_aproduct= new ArrayList<String>();
ArrayList<String> o_aqty= new ArrayList<String>();
ArrayList<String> o_atotal= new ArrayList<String>();
private class fetchorder extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("v_username", uid));
JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);
int success1 = Integer.parseInt(json.getString("success4"));
Log.d("success4", json.toString());
if (success1 == 0) {}
if (success1 == 1) {
o_aid.clear();
o_aproduct.clear();
o_aqty.clear();
o_atotal.clear();
ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
o_aid.add(jsonobject.getString("o_id"));
o_aproduct.add(jsonobject.getString("o_product"));
o_aqty.add(jsonobject.getString("o_qty"));
o_atotal.add(jsonobject.getString("o_total"));
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
if (listadapter == null) {
listadapter = new ListViewAdapterorder(getApplicationContext(), o_aid, o_aproduct, o_aqty, o_atotal);
listview.setAdapter(listadapter);
} else {
listadapter.notifyDataSetChanged();
}
}
}
public void onStart() {
super.onStart();
BackTask bt = new BackTask();
bt.execute();
}
private class BackTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected void onPreExecute() {
super.onPreExecute();
list = new ArrayList<>();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/portal/spinner.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result += line;
}
is.close();
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
list.add("Please Select Model");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
// add interviewee name to arraylist
list.add(jsonObject.getString("m_model"));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
listItems.addAll(list);
}
}
}
Here MainActivity.java ListView class
ArrayList<String> o_aid= new ArrayList<String>();
ArrayList<String> o_aproduct= new ArrayList<String>();
ArrayList<String> o_aqty= new ArrayList<String>();
ArrayList<String> o_atotal= new ArrayList<String>();
private class fetchorder extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... args) {
try {
arraylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("v_username", uid));
JSONObject json = jParser.makeHttpRequest(url_visitor, "GET", params);
int success1 = Integer.parseInt(json.getString("success4"));
Log.d("success4", json.toString());
if (success1 == 0) {}
if (success1 == 1) {
o_aid.clear();
o_aproduct.clear();
o_aqty.clear();
o_atotal.clear();
ownerObj = json.getJSONArray("visit");
for (int i = 0; i < ownerObj.length(); i++) {
jsonobject = ownerObj.getJSONObject(i);
o_aid.add(jsonobject.getString("o_id"));
o_aproduct.add(jsonobject.getString("o_product"));
o_aqty.add(jsonobject.getString("o_qty"));
o_atotal.add(jsonobject.getString("o_total"));
}
}
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
if (listadapter == null) {
listadapter = new ListViewAdapterorder(getApplicationContext(), o_aid, o_aproduct, o_aqty, o_atotal);
listview.setAdapter(listadapter);
} else {
listadapter.notifyDataSetChanged();
}
}
}
I tried this way but the delete is not happening.. please suggest me some coede for this.
Try this.
Delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
datlist.remove(position);
o_aid.remove(position);
o_aproduct.remove(position);
o_aqty.remove(position);
o_atotal.remove(position);
Snackbar.make(view, "Record Delete Succesfully", Snackbar.LENGTH_LONG).show();
notifyDataSetChanged();
}
});
Call me:85110 51548 if any issue
There is issue in your connection.php pls check I have checked but not issue from php queries but if connection.php has issue you will not find because if record is deleted it returns 1 if any problem it returns 0 in your code return 0 it means record is not deleted successfully.
Write The Following Code in Your php and change it into connection.php
/*connection.php */
$host="your host";
$username="your user name";
$password="your password";
$dbname="your database name";
$con = new mysqli($host, $username, $password,$dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
/*code.php */
include('connection.php');
$tbl = "abc";
$idToDelete = $_GET["id"];
$sql="DELETE FROM $tbl WHERE o_id=".$idToDelete;
$delete_row = $con->query($sql);
$response["delete"] = array();
$response["success"]=1;
/// push single product into final response array
echo json_encode($response);
** In short there is a problem in connection file thats why not deleted that record **
I am searching for places nearby my current location (found by GPS). When a user clicks on the marker of a place nearby, a new activity starts (PlaceDetailsActivity), which shows details of the place. But when the info window of the marker of my current location is pressed, the app crashes. How can I solve this problem?
My MainActivity.java
package com.example.mobiletourismapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;
import android.animation.ValueAnimator;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity implements LocationListener{
GoogleMap mGoogleMap;
Spinner mSprPlaceType;
String[] mPlaceType=null;
String[] mPlaceTypeName=null;
double mLatitude=0;
double mLongitude=0;
HashMap<String, String> mMarkerPlaceLink = new HashMap<String, String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Array of place types
mPlaceType = getResources().getStringArray(R.array.place_type);
// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
// Getting reference to the Spinner
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
// Setting adapter on Spinner to set place types
mSprPlaceType.setAdapter(adapter);
Button btnFind;
// Getting reference to Find Button
btnFind = ( Button ) findViewById(R.id.btn_find);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment
SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Google Map
mGoogleMap = fragment.getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
mGoogleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
Intent intent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
String reference = mMarkerPlaceLink.get(arg0.getId());
intent.putExtra("reference", reference);
// Starting the Place Details Activity
startActivity(intent);
}
});
// Setting click event lister for the find button
btnFind.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=3000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=AIzaSyB6f_n3Z9877pSGkV6XhHXsJtfCmetJqCM");
// Creating a new non-ui thread task to download Google place json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
});
}
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result){
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
private Location location;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String,String>> list){
// Clears all the existing markers
mGoogleMap.clear();
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin));
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
markerOptions.snippet("Click here for more info...");
// Placing a marker on the touched position
Marker m = mGoogleMap.addMarker(markerOptions);
// Linking Marker id and place reference
mMarkerPlaceLink.put(m.getId(), hmPlace.get("reference"));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.addMarker (new MarkerOptions()
.title ("You are here")
.snippet("Current location")
.position(latLng)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.gps)
));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); // Showing current location in map
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
PlaceDetailsActivity
package com.example.mobiletourismapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
public class PlaceDetailsActivity extends Activity {
WebView mWvPlaceDetails;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_details);
// Getting reference to WebView ( wv_place_details ) of the layout activity_place_details
mWvPlaceDetails = (WebView) findViewById(R.id.wv_place_details);
mWvPlaceDetails.getSettings().setUseWideViewPort(false);
// Getting place reference from the map
String reference = getIntent().getStringExtra("reference");
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/details/json?");
sb.append("reference="+reference);
sb.append("&sensor=true");
sb.append("&key=AIzaSyB6f_n3Z9877pSGkV6XhHXsJtfCmetJqCM");
// Creating a new non-ui thread task to download Google place details
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
};
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Google Place Details */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result){
ParserTask parserTask = new ParserTask();
// Start parsing the Google place details in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Google Place Details in JSON format */
private class ParserTask extends AsyncTask<String, Integer, HashMap<String,String>>{
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected HashMap<String,String> doInBackground(String... jsonData) {
HashMap<String, String> hPlaceDetails = null;
PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
// Start parsing Google place details in JSON format
hPlaceDetails = placeDetailsJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return hPlaceDetails;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(HashMap<String,String> hPlaceDetails){
String name = hPlaceDetails.get("name");
String icon = hPlaceDetails.get("icon");
String vicinity = hPlaceDetails.get("vicinity");
String lat = hPlaceDetails.get("lat");
String lng = hPlaceDetails.get("lng");
String formatted_address = hPlaceDetails.get("formatted_address");
String formatted_phone = hPlaceDetails.get("formatted_phone");
String website = hPlaceDetails.get("website");
String rating = hPlaceDetails.get("rating");
String international_phone_number = hPlaceDetails.get("international_phone_number");
String url = hPlaceDetails.get("url");
String mimeType = "text/html";
String encoding = "utf-8";
String data = "<html>"+
"<body><img style='float:left' src="+icon+" /><h1><center>"+name+"</center></h1>" +
"<br style='clear:both' />" +
"<hr />"+
"<p>Vicinity : " + vicinity + "</p>" +
"<p>Location : " + lat + "," + lng + "</p>" +
"<p>Address : " + formatted_address + "</p>" +
"<p>Phone : " + formatted_phone + "</p>" +
"<p>Website : " + website + "</p>" +
"<p>Rating : " + rating + "</p>" +
"<p>International Phone : " + international_phone_number + "</p>" +
"<p>URL : <a href='" + url + "'>" + url + "</p>" +
"</body></html>";
// Setting the data in WebView
mWvPlaceDetails.loadDataWithBaseURL("", data, mimeType, encoding, "");
}
}
}
Finally I did that to solve my issue and it worked.
mGoogleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
if (marker.getSnippet().equals("Current location")){
}
else{
Intent intent = new Intent(getBaseContext(), PlaceDetailsActivity.class);
String reference = mMarkerPlaceLink.get(marker.getId());
intent.putExtra("reference", reference);
startActivity(intent); // Starting the Place Details Activity
}
}
});........................
Hi I'm having an issue trying to retrieve information from an async task.
What I'm trying to achieve is get the lng/lat from a postcode and then display them on a map. Getting the lng/lat works fine, its just I cant work out how to get that information from the onPostExecute back to the onCreate in an array.
I can perform a loop to add the map markers there.
Anyone know how I go about this?
Updated code
This is the working code that also updates the zoom to fit all entries in. Might help some people out
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import com.example.coreoffice.library.GeocodeJSONParser;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.LatLngBounds.Builder;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity
{
Button mBtnFind;
static GoogleMap mMap;
EditText etPlace;
private static final String TAG = "MainActivity";
static ArrayList<Double> lat = new ArrayList<Double>();
static ArrayList<Double> lng = new ArrayList<Double>();
static Builder bounds = new LatLngBounds.Builder();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_maps);
Log.v(TAG + "onCreate", "onCreate call");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFragment.getMap();
String[] location =
{ "WA32ED", "M30oft", "W21AA" }; // address
String url;
for (int i = 0; i < location.length; i++)
{
DownloadTask downloadTask = new DownloadTask();
url = "";
url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + location[i] + "&sensor=false";
Log.v("URL", url);
downloadTask.execute(url);
}
}
public static void processMap()
{
for (int i = 0; i < lat.size(); i++)
{
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat.get(i), lng.get(i));
markerOptions.position(latLng);
markerOptions.title("title");
mMap.addMarker(markerOptions);
bounds.include(new LatLng(lat.get(i), lng.get(i)));
}
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds.build(), 100));
}
private String downloadUrl(String strUrl) throws IOException
{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try
{
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null)
{
sb.append(line);
}
data = sb.toString();
br.close();
}
catch (Exception e)
{
Log.d("Exception while downloading url", e.toString());
}
finally
{
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class DownloadTask extends AsyncTask<String, Integer, String>
{
String data = null;
#Override
protected String doInBackground(String... url)
{
try
{
data = downloadUrl(url[0]);
}
catch (Exception e)
{
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result)
{
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>>
{
JSONObject jObject;
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData)
{
List<HashMap<String, String>> places = null;
GeocodeJSONParser parser = new GeocodeJSONParser();
try
{
jObject = new JSONObject(jsonData[0]);
places = parser.parse(jObject);
}
catch (Exception e)
{
Log.d("Exception", e.toString());
}
return places;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> list)
{
for (int i = 0; i < list.size(); i++)
{
HashMap<String, String> hmPlace = list.get(i);
double lat = Double.parseDouble(hmPlace.get("lat"));
double lng = Double.parseDouble(hmPlace.get("lng"));
MapsActivity.this.lat.add(lat);
MapsActivity.this.lng.add(lng);
MapsActivity.processMap();
Log.v("lat", Double.toString(lat));
Log.v("lng", Double.toString(lng));
}
}
}
}
As your AsyncTasks are, by definition, asynchronous, you cannot guarantee that they will be done before onCreate() finishes. You merely need to call a method in onPostExecute() of ParserTask to handle the "loop" you describe after the tasks have completed.
Your ArrayLists lat and lng are accessible to the inner classes that are your AsyncTasks, so you just need to add a few lines to onPostExecute():
protected void onPostExecute(List<HashMap<String, String>> list)
{
for (int i = 0; i < list.size(); i++)
{
HashMap<String, String> hmPlace = list.get(i);
double lat = Double.parseDouble(hmPlace.get("lat"));
double lng = Double.parseDouble(hmPlace.get("lng"));
MapsActivity.this.lat.add(lat);
MapsActivity.this.lng.add(lng);
Log.v("lat", Double.toString(lat));
Log.v("lng", Double.toString(lng));
}
processData();
}
Then create a method in MapsActivity:
private void processData()
{
// Do your loop here.
}
You can define an interface as callback for your ParserTask class, and call it in onPostExecute method.
First declare an interface:
public interface OnParseFinishedListener {
public void onFinished(/* required params */);
}
Then add these methods to your ParserTask:
public void setOnParseFinishedListener(OnParseFinishedListener listener){
this.listener = listener;
}
and in your onPostExecute add this line:
if(listener != null) {
listener.onFinished(/* pass params here! */);
}
Use a global variable to hold your HashMap, and then pass it from your Activity into your AsyncTask.
you Should do the donwloading and parsing in a single asynctask.
I would propose using loader instead of asynctask (as you will have a problem once your asynctask returns and your activity has been recreated (eg due to turning the screen or any other configuration change)
In onPostExecute you just call a method in your activity. There you can access your map object /fragment (which you store in an instance variable in onCreate).
Again use an asyncloader which behaves very similar to asynctask but will save you a lot of grief down the line even if it's slightly more complex in the beginning.