I'm trying to change multiple Google Maps marker icon based on urls i get from a webserver. Since I Previously only worked with web applications this is very new to me.
I have read in other topics that i have to create a new thread, but if I want to get multiple photos doesn't that become a problem? Does anyone have a suggestion for my problem?
here is my code:
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
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.BitmapDescriptorFactory;
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 org.json.JSONArray;
import org.json.JSONException;
public class Mainmap extends ActionBarActivity implements View.OnClickListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private LocationManager location;
private String provider;
private double lat;
private double lng;
private double pic_lat;
private double pic_lng;
private String image;
public static String LOG_TAG = "cn-quotes";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainmap);
location = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria c = new Criteria();
provider = location.getBestProvider(c, false);
setUpMapIfNeeded();
View newPhoto = findViewById(R.id.button_local_position);
newPhoto.setOnClickListener(this);
View popPhoto =findViewById(R.id.button_popphoto);
popPhoto.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
// startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
location.requestLocationUpdates(provider, 300000, 1000, onLocationChange);
setUpMapIfNeeded();
}
LocationListener onLocationChange=new LocationListener() {
public void onLocationChanged(Location location) {
lng = location.getLongitude();
lat = location.getLatitude();
}
public void onProviderDisabled(String provider) {
// required for interface, not used
}
public void onProviderEnabled(String provider) {
// required for interface, not used
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
// required for interface, not used
}
};
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setMapType(mMap.MAP_TYPE_HYBRID);
mMap.setMyLocationEnabled(true);
if (lat != 0) {
LatLng latLng = new LatLng(lat, lng);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
Log.d("DEBUG", "succes");
} else {
Log.d("DEBUG", "fail");
}
}
private void downloadJSON(String downloadurl) {
new JSONDownloader(this, downloadurl).execute();
}
public void updatephotos(JSONArray result) {
Log.d("Debug arraylength", "" + result.length());
for (int i = 0; i < result.length(); i++) {
try {
pic_lat = result.getJSONObject(i).getDouble("latitudes");
pic_lng = result.getJSONObject(i).getDouble("longtitudes");
image = result.getJSONObject(i).getString("images");
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)));
} catch (JSONException e) {
Log.e(Mainmap.LOG_TAG, "JSONException", e);
}
}
}
#Override
public void onClick(View v) {
String downloadurl = "";
switch (v.getId())
{
case R.id.button_popphoto:
downloadurl = "index.php";
break;
case R.id.button_local_position:
downloadurl = "index.php?yourLat=" + lat + "&yourLng=" + lng;
break;
}
downloadJSON(downloadurl);
}
}
And the JSONdownloader:
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class JSONDownloader extends AsyncTask<Void, Void, JSONArray> {
private Mainmap mm;
private String downloadurl = "http://student.cmi.hro.nl/0876538/Jaar1/Kwartaal3/IMP03/huiswerk/week04/opdracht/libs/php/";
public JSONDownloader(Mainmap mm, String url) {
this.mm = mm;
this.downloadurl = downloadurl + url;
}
public JSONArray getPhotos() {
JSONArray result = new JSONArray();
HttpURLConnection con = null;
Log.d(Mainmap.LOG_TAG, "Getting photos");
try {
Log.d(Mainmap.LOG_TAG, downloadurl);
URL url = new URL(downloadurl);
con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setRequestMethod("GET");
con.setDoInput(true);
con.connect();
BufferedReader reader = new BufferedReader(
new InputStreamReader(con.getInputStream(), "UTF-8"));
String payload = reader.readLine();
reader.close();
result = new JSONArray(payload);
} catch (IOException e) {
Log.e(Mainmap.LOG_TAG, "IOException", e);
} catch (JSONException e) {
Log.e(Mainmap.LOG_TAG, "JSONException", e);
} catch (Exception e) {
Log.d(Mainmap.LOG_TAG, "Something went wrong....", e);
} finally {
if (con != null) {
con.disconnect();
}
}
Log.d(Mainmap.LOG_TAG, "-> returned: " + result);
return result;
}
#Override
protected JSONArray doInBackground(Void... params) {
JSONArray photos = getPhotos();
return photos;
}
#Override
protected void onPostExecute(JSONArray result) {
super.onPostExecute(result);
mm.updatephotos(result);
}
}
Related
I am trying to create an app that sends to my server the location of my android device on button press. Unfortunately the location updates very slowly, sometimes taking minutes and tens of meters to get the new location.
I'm relatively new to Android programming and if anyone could help me with a way to update the location every time when press the send button I would be grateful.
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import org.json.*;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
public class DefaultActivity extends AppCompatActivity {
private String serverURL;
private TextView tv_Title, tv_Status;
private Button b_SendLocation, b_SendNow, b_StopLocation;
private User user;
private FusedLocationProviderClient locationClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_default);
Intent intent = getIntent();
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
locationClient = LocationServices.getFusedLocationProviderClient(this);
serverURL = intent.getExtras().getString("serverURL");
JSONParse(intent.getExtras().getString("myResponse"));
tv_Title = findViewById(R.id.TextView_Title);
tv_Status = findViewById(R.id.TextView_Status);
b_SendLocation = findViewById(R.id.Button_SendLocation);
b_SendNow = findViewById(R.id.Button_SendNow);
b_StopLocation = findViewById(R.id.Button_StopLocation);
tv_Title.setText(user.getLastName() + " " + user.getFirstName());
tv_Status.setText(" ");
b_SendLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Feedback("Sending location every 5 sec.");
}
});
b_SendNow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Feedback("Current location sent!");
GetLocation();
}
});
b_StopLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Feedback("Periodic sending halted!");
}
});
}
private void GetLocation() {
if (ActivityCompat.checkSelfPermission(DefaultActivity.this, ACCESS_FINE_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;
}
locationClient.getLastLocation().addOnSuccessListener(DefaultActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null){
double latitude, longitude;
latitude = location.getLatitude();
longitude = location.getLongitude();
tv_Status.setText("Latitude: " + latitude + "\nLongitude: " + longitude);
SendLocation(latitude, longitude);
}
else
tv_Status.setText("Location is null!");
}
});
}
private void SendLocation(double latitude, double longitude){
OkHttpClient client = new OkHttpClient();
String url = serverURL + "/api/user/?id=" + user.getID() + "&latitude=" + latitude + "&longitude=" + longitude;
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e){
e.printStackTrace();
runOnUiThread(new Runnable() {
#Override
public void run() {
tv_Status.append("\n\n Server error!");
}
});
}
#Override
public void onResponse(Call call, Response response) throws IOException{
if (response.isSuccessful()){
runOnUiThread(new Runnable() {
#Override
public void run() {
tv_Status.append("\n\n Server acknowledged!");
}
});
}
}
});
}
private void JSONParse(String JSONString){
User readUser = new User();
try {
JSONObject obj = new JSONObject(JSONString);
readUser.setID(Integer.parseInt(obj.getString("ID")));
readUser.setFirstName(obj.getString("FirstName"));
readUser.setLastName(obj.getString("LastName"));
readUser.setEmail(obj.getString("Email"));
readUser.setPassword(obj.getString("Password"));
readUser.setRole(obj.getString("Role"));
Feedback("Welcome back " + readUser.getFirstName() + "!");
} catch (JSONException e) {
Feedback("JSON Exception!");
e.printStackTrace();
}
user = readUser;
}
private void Feedback(String message){
Toast toast=Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG);
toast.show();
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
private String getMapsApiDirectionsUrl() {
String origin;
String destination=String.valueOf(l.longitude)+","+String.valueOf(l.latitude);
origin=String.valueOf(longitude)+","+String.valueOf(latitude);
// String url = "https://maps.googleapis.com/maps/api/directions/"+ output + "?" + params;
String url="https://maps.googleapis.com/maps/api/directions/json?origin="+origin+"&destination="+destination+"&sensor=false";
return url;
}
I am getting NullPointerException. I know what it is but not able to identify what is causing it. Assuming everything outside this method is correct, what is wrong syntactically?
This is my entire code:
package autogenie.maptrial;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
public class MainActivity extends FragmentActivity implements LocationListener,GoogleMap.OnMarkerDragListener {
private double latitude, longitude;
public GoogleMap googleMap,googleMap1;
LocationManager locationManager;
Button addressButton;
PlaceAutocompleteFragment fragment;
LatLng l;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = supportMapFragment.getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
addressButton = (Button) findViewById(R.id.addressButton);
fragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
String url = getMapsApiDirectionsUrl();
ReadTask downloadTask = new ReadTask();
downloadTask.execute(url);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
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;
}
addressButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText editText = (EditText) findViewById(R.id.enter_place_name);
String address = editText.getText().toString();
GeocodingLocation locationAddress = new GeocodingLocation();
locationAddress.getAddressFromLocation(address,
getApplicationContext(), new GeocoderHandler());
l= getLocationFromAddress(getApplicationContext(), address);
MarkerOptions a=new MarkerOptions().position(l);
Marker m=googleMap.addMarker(a);
m.setPosition(l);
}
});
fragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) { // Handle the selected Place
}
#Override
public void onError(Status status) { // Handle the error
}
});
}
public LatLng getLocationFromAddress(Context context,String strAddress) {
Geocoder coder = new Geocoder(context,Locale.getDefault());
List<Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(strAddress, 1);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new LatLng(location.getLatitude(), location.getLongitude() );
} catch (Exception ex) {
ex.printStackTrace();
}
return p1;
}
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
String locationAddress;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationAddress = bundle.getString("address");
break;
default:
locationAddress = null;
}
Toast.makeText(getApplicationContext(),locationAddress,Toast.LENGTH_LONG).show();
}
}
#Override
public void onLocationChanged(Location location) {
if (location == null) {
latitude = 28.608426;
longitude = 77.225168;
} else {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
String s = "longitude:" + longitude + "latitude:" + latitude;
Log.i("Current location", " latlong value" + s);
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Hello world"));
/*CameraUpdate center =
CameraUpdateFactory.newLatLng(new LatLng(latitude,
-longitude));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(10);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
//dfg
private String getMapsApiDirectionsUrl() {
// String url = "https://maps.googleapis.com/maps/api/directions/"+ output + "?" + params;
String url="https://maps.googleapis.com/maps/api/directions/json?origin="+l+"&destination="+latitude+","+longitude+"&sensor=false";
return url;
}
private class ReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String data = "";
try {
HttpConnection http = new HttpConnection();
data = http.readUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
#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]);
PathJSONParser parser = new PathJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
ArrayList<LatLng> points = null;
PolylineOptions polyLineOptions = null;
// traversing through routes
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<LatLng>();
polyLineOptions = new PolylineOptions();
List<HashMap<String, String>> path = routes.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(2);
polyLineOptions.color(Color.BLUE);
}
googleMap.addPolyline(polyLineOptions);
}
}
class GeocodingLocation {
private static final String TAG = "GeocodingLocation";
public String result1,result2;
public void getAddressFromLocation(final String locationAddress,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List
addressList = geocoder.getFromLocationName(locationAddress, 1);
if (addressList != null && addressList.size() > 0) {
Address address = (Address) addressList.get(0);
StringBuilder sb = new StringBuilder();
sb.append(address.getLatitude()).append("\n");
sb.append(address.getLongitude()).append("\n");
result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable to connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n\nLatitude and Longitude :\n" + result;
bundle.putString("address", result);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n Unable to get Latitude and Longitude for this address location.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
}
Stack Trace:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.google.maps.api.android.lib6.e.aw.<init>(Unknown Source)
at com.google.maps.api.android.lib6.e.ev.a(Unknown Source)
at com.google.android.gms.maps.internal.j.onTransact(SourceFile:137)
at android.os.Binder.transact(Binder.java:310)
at com.google.android.gms.maps.internal.IGoogleMapDelegate$zza$zza.addPolyline(Unknown Source)
at com.google.android.gms.maps.GoogleMap.addPolyline(Unknown Source)
at autogenie.maptrial.MainActivity$ParserTask.onPostExecute(MainActivity.java:315)
at autogenie.maptrial.MainActivity$ParserTask.onPostExecute(MainActivity.java:267)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method) 01-21 12:24:35.291 3683-3683/autogenie.maptrial I/Process: Sending signal. PID: 3683 SIG: 9
one of your variables(l, latitude, longitude) is null since the only place that might cause the exception is the valueOf calls.
I'm new to android and I'm creating an application based on GPS . So i have implement Google maps and location point identifier on my application but it takes only my first attempt geo location , when I'm moving it is not get updated . please help me to solve this . Thank you.
package com.android.locationtracker;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.android.app.AppConst;
import com.android.app.AppController;
import com.android.common.GPSTracker;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
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.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
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.android.gms.maps.model.PolylineOptions;
public class NearByActivity extends Activity {
private static final String TAG = "error";
private GoogleMap googleMap;
private static String URL = AppConst.GEOMETRY;
private static String URL_UPDATE = AppConst.GEOMETRY_UPDATE;
private String jsonResponse;
private ProgressDialog pDialog;
GPSTracker gps;
double latitude;
double longtitude;
String id;
String type;
List<Marker> markerList = new ArrayList<Marker>();
Marker marker;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nearby_activity);
try {
// Loading map
initilizeMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
gps = new GPSTracker(this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longtitude = gps.getLongtitude();
} else {
gps.showSettingAllerts();
}
new LoadGeo().execute();
}
private void initilizeMap() {
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onResume() {
super.onResume();
initilizeMap();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
private class LoadGeo extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NearByActivity.this);
pDialog.setMessage("Loading...");
pDialog.show();
//
}
#Override
protected Void doInBackground(Void... arg0) {
SharedPreferences prefs = getSharedPreferences("conetext",
Context.MODE_PRIVATE);
id = prefs.getString("userid", null);
type = prefs.getString("persontype", null);
Map<String, String> params = new HashMap<String, String>();
params.put("userid", id);
params.put("usertype", type);
params.put("lat", String.valueOf(latitude));
params.put("lng", String.valueOf(longtitude));
JsonObjectRequest req = new JsonObjectRequest(URL_UPDATE,
new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("map", "msg");
VolleyLog.v("Response:%n %s",
response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
AppController.getInstance().addToRequestQueue(req);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Thread thread = new Thread() {
#Override
public void run() {
try {
while (true) {
sleep(1000);
JsonArrayRequest req = new JsonArrayRequest(URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(
JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
markerList.clear();
googleMap.clear();
for (int i = 0; i < response
.length(); i++) {
JSONObject geo = (JSONObject) response
.get(i);
String usertype = geo
.getString("UserType");
MarkerOptions markerblue = new MarkerOptions();
markerblue.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
markerblue.position(new LatLng(latitude, longtitude));
googleMap.addMarker(markerblue);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
latitude, longtitude), 17));
if (usertype
.equals("driver")) {
double lat = geo
.getDouble("Lat");
double lng = geo
.getDouble("Lng");
MarkerOptions markerop = new MarkerOptions();
markerop.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
markerop.position(
new LatLng(lat,
lng))
.draggable(true)
.visible(true);
marker= googleMap
.addMarker(markerop);
markerList.add(marker);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(
getApplicationContext(),
"Error: "
+ e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(
VolleyError error) {
VolleyLog.d(
TAG,
"Error: "
+ error.getMessage());
Toast.makeText(
getApplicationContext(),
error.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
}
}
You need to register LocationListener and implement method
#Override
public void onLocationChanged(Location location) {
//smth like this
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongtitude()), 17));
}
detailed info is here https://developer.android.com/training/location/receive-location-updates.html
You need to execute this code in specific interval
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longtitude = gps.getLongtitude();
} else {
gps.showSettingAllerts();
}
new LoadGeo().execute();
i would suggest use Handler.postDelayed(Runnable,Interval) method to work this out.
You can use Location service. Here is the code for that:
Call this function by giving a desired frequency (in mins):
private void requestLocation(Context context, int frequency) //frequency in mins
{
LocationMgr loc_mgr = new LocationMgr(context);
loc_mgr.requestLocationUpdates(frequency);
}
Here is the LocationMgr class:
public class LocationMgr implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
{
private final Context context;
private GoogleApiClient googleApiClient;
private boolean inProgress;
public enum REQUEST_TYPE {START, STOP, LAST_KNOWN}
private REQUEST_TYPE requestType;
private Intent intent;
LocationRequest mLocationRequest;
LocationListener ll;
public LocationMgr(Context context)
{
this.context = context;
this.googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
intent = new Intent(context, LocationService.class);
inProgress = false;
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
inProgress = false;
}
#Override
public void onConnectionSuspended(int arg0) {
googleApiClient.connect();
}
#Override
public void onConnected(Bundle connectionHint) {
PendingIntent pendingIntent = PendingIntent.getService(context, 123, intent, PendingIntent.FLAG_UPDATE_CURRENT);
switch (requestType)
{
case START :
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, pendingIntent);
break;
case STOP :
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, pendingIntent);
break;
case LAST_KNOWN :
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
ll.onNewLocationUpdate(location);
break;
default :
log.e("Unknown request type in onConnected().");
break;
}
inProgress = false;
googleApiClient.disconnect();
}
/**
*
* #param frequency (minutes) minimum time interval between location updates
*/
public void requestLocationUpdates(int frequency)
{
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(frequency * 60 * 1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(1000);
if (inProgress)
{
log.e("A request is already underway");
return;
}
inProgress = true;
requestType = REQUEST_TYPE.START;
googleApiClient.connect();
}
public void removeContinuousUpdates()
{
if (inProgress)
{
log.e("A request is already underway");
return;
}
inProgress = true;
requestType = REQUEST_TYPE.STOP;
googleApiClient.connect();
}
public void getLastKnownLocation(LocationListener ll)
{
this.ll = ll;
if (inProgress)
{
log.e("A request is already underway");
return;
}
inProgress = true;
requestType = REQUEST_TYPE.LAST_KNOWN;
googleApiClient.connect();
}
}
Here is the LocationService class:
public class LocationService extends IntentService
{
public LocationService()
{
super("NOTIFICATION_SERVICE");
}
/**
* Called when a new location update is available.
*/
#Override
protected void onHandleIntent(Intent intent)
{
LocationListener ll = new LocationListener()
{
#Override
public void onNewLocationUpdate(Location location)
{
// here you will get the latest location
}
};
LocationMgr lm = new LocationMgr(getApplicationContext());
lm.getLastKnownLocation(ll);
}
}
In my application am loading 1000+ location form JSON to google map using markers but when i run my application it shows all the markers perfectly but when i tried to zoom or drag the map it get two slow and get struck any solution to solve this ??
The webservice response looks like this given below
{
"DateTime": "8/4/2015 7:27:32 PM",
"IME": "865733024065062",
"IsActivated": null,
"Latitude": "13.0115833333333",
"Longitude": "80.2151833333333",
"RegistrationNo": "AMvTS_01"
},
{
"DateTime": "8/5/2015 12:28:17 PM",
"IME": "887766554433711",
"IsActivated": null,
"Latitude": "16.060578",
"Longitude": "73.489748",
"RegistrationNo": "TN_TEST_803"
},
{
"DateTime": "8/5/2015 12:28:17 PM",
"IME": "887766554433567",
"IsActivated": null,
"Latitude": "9.722656",
"Longitude": "76.287158",
"RegistrationNo": "TN_TEST_659"
},
{
"DateTime": "8/5/2015 12:28:17 PM",
"IME": "887766554433740",
"IsActivated": null,
"Latitude": "14.895189",
"Longitude": "74.103996",
"RegistrationNo": "TN_TEST_832"
},
{
"DateTime": "8/5/2015 12:28:17 PM",
"IME": "887766554433017",
"IsActivated": null,
"Latitude": "12.688946",
"Longitude": "80.217097",
"RegistrationNo": "TN_TEST_048"
},
{
"DateTime": "8/5/2015 12:28:17 PM",
"IME": "887766554433769",
"IsActivated": null,
"Latitude": "8.887102",
"Longitude": "76.591018",
"RegistrationNo": "TN_TEST_861"
}
and this is my mapfragment code given below
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.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
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;
import com.google.android.gms.maps.model.PolylineOptions;
import android.app.ActionBar;
import android.app.AlarmManager;
import android.app.Fragment;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class MapFragment extends Fragment implements LocationListener, OnMapClickListener, OnMapLongClickListener, OnMarkerDragListener{
private static final String LOG_TAG = "ExampleApp";
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
private static final String SERVICE_URL = "http://203.109.107.139/primevts/vtsservice.svc/data";
JSONObject json = null;
JSONArray jsonarray = null;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist1;
private Timer timer;
static String LONG = "Long";
static String LAT = "Lat";
ArrayList<String> ct;
public double latt = 0;
public double lng = 0;
public ArrayList<Integer> dLat;
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
private Handler handler;
private Marker marker;
private HashMap<String, Marker> mMarkers = new HashMap<>();
int value=1;
// LatLngBounds values ;
double latitude, longitude;
String ime,reg;
boolean markerClicked;
// LatLng val;
static HashMap<String, String> datas;
static HashMap<String, String> map;
String[] latlngvalues;
// LocationManager locman;
Context context;
View rootView;
public MapFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout_one, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView)rootView.findViewById(R.id.mapView);
mMapView.onCreate(mBundle);
MapsInitializer.initialize(getActivity());
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
/* handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
Log.e("Data in Log", "");
}
}, 1000);
*/
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
//mMap.clear();
// Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
}
});
}
};
timer.schedule(doAsynchronousTask, 20000, 20000);
/*LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
//locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);*/
return rootView;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.setMyLocationEnabled(true);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Marker")
.draggable(true)
.snippet("Hello")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)));
mMap.setOnMarkerDragListener(this);
markerClicked = false;
Location myLocation = mMap.getMyLocation();
if (mMap != null) {
//mMap.clear();
// setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
// mMap.clear();
if(marker!=null){
marker.remove();
}
for (int i = 0; i < arraylist1.size(); i++) {
final LatLng position = new LatLng(Double
.parseDouble(arraylist1.get(i).get("Latitude")),
Double.parseDouble(arraylist1.get(i).get(
"Longitude")));
String ime1 = arraylist1.get(i).get("RegistrationNo");
final MarkerOptions options = new MarkerOptions()
.position(position);
//mMap.addMarker(options);
mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).anchor(0.0f, 1.0f).title(ime1));
// marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
//options.title(ime1);
builder.include(position);
} if(value==1){
LatLng latLng = new LatLng(arg0.getLatitude(), arg0
.getLongitude());
//mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.setMyLocationEnabled(true);
//mMap.moveCamera(CameraUpdateFactory.newLatLng(newLatLnglatLng));
// mMap.setOnMapClickListener(null);
mMap.setOnMarkerClickListener(null);
//mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng) // Sets the center of the map to Mountain View
.zoom(10) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
value++;
}
}
});
}
}
}
/* protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
new DownloadJSON().execute();
} */
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
String result="";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
arraylist1 = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
String result = "";
json = jParser.getJSONFromUrl(SERVICE_URL);
try {
arraylist1.clear();
jsonarray = json.getJSONArray("SingleIMEs");
Log.d("Haaaaaaaaaaaa", "" + json);
for (int i = 0; i < jsonarray.length(); i++) {
Log.d("H11111111111111111111111111",
"" + jsonarray.length());
map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
latitude = json.getDouble("Latitude");
longitude = json.getDouble("Longitude");
ime = json.getString("IME");
reg=json.getString("RegistrationNo");
map.put("Latitude", json.getString("Latitude"));
Log.e("CHECKLAT",""+json.getString("Latitude") );
map.put("Longitude", json.getString("Longitude"));
Log.e("CHECKLONG",""+json.getString("Longitude") );
map.put("RegistrationNo", json.getString("RegistrationNo"));
map.put("IME", json.getString("IME"));
arraylist1.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
result="Error";
e.printStackTrace();
}
}catch(Exception e){
result="Error";
}
return null;
}
protected void onPostExecute(Void args) {
// mProgressDialog.dismiss();
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
/* Toast.makeText(getActivity(), "onLocationUpdated!!!", Toast.LENGTH_SHORT).show();
Log.d("onLocationUpdated!!!","");
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onMapClick(LatLng arg0) {
// TODO Auto-generated method stub
mMap.animateCamera(CameraUpdateFactory.newLatLng(arg0));
markerClicked = false;
}
#Override
public void onMarkerDrag(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMarkerDragEnd(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMarkerDragStart(Marker arg0) {
// TODO Auto-generated method stub
}
#Override
public void onMapLongClick(LatLng arg0) {
// TODO Auto-generated method stub
}
}
First you save in List of MarkerOptions your JSON info, when you get it
final List<MarkerOptions> markerOptionsList = new ArrayList<>(arraylist1.size());
for (int i = 0; i < arraylist1.size(); i++) {
final LatLng position = new LatLng(
Double.parseDouble(arraylist1.get(i).get("Latitude")),
Double.parseDouble(arraylist1.get(i).get("Longitude")));
String ime1 = arraylist1.get(i).get("RegistrationNo");
final MarkerOptions options = new MarkerOptions()
.position(position)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.buspng))
.anchor(0.0f, 1.0f)
.title(ime1);
markerOptionsList.add(options);
}
Then, instead of OnMyLocationChangeListener use OnCameraChangeListener
mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition cameraPosition) {
mMap.clear();
LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds;
for (MarkerOptions markerOptions : markerOptionsList) {
if (bounds.contains(markerOptions.getPosition())) {
mMap.addMarker(markerOptions);
}
}
}
});
You will clear map and add only visible markers
I have an app that shows user's current location on google map, the app runs in emulator (though it doesn't show location) however it crashes in real device.
Here is the error I'm getting
01-04 15:00:59.509 26494-26494/io.xgear.geotag E/AndroidRuntime: FATAL
EXCEPTION: main java.lang.RuntimeException: Unable to start activity
ComponentInfo{io.xgear.geotag/io.xgear.geotag.MainActivity}:
java.lang.NullPointerException
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
at android.app.ActivityThread.access$1500(ActivityThread.java:121)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at io.xgear.geotag.MainActivity.onCreate(MainActivity.java:72)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
at android.app.ActivityThread.access$1500(ActivityThread.java:121)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
at dalvik.system.NativeStart.main(Native Method)
and here's my code for main activity
package io.xgear.geotag;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import android.support.v4.app.Fragment;
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.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import io.xgear.geotag.helper.Post;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
private GeoTagTask mAuthTask = null;
//GPSTracker gps;
private JSONObject jsonObj;
// UI references.
private EditText txtShopCode;
private EditText lblAddress;
private View mProgressView;
private View mGeoTagForm;
private Button btnGeoTag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
txtShopCode = (EditText) findViewById(R.id.txtShopCode);
btnGeoTag = (Button) findViewById(R.id.btnGeoTag);
mGeoTagForm = (View) findViewById(R.id.geoTagForm);
mProgressView = findViewById(R.id.geoTagProgress);
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
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;
}
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
// gps = new GPSTracker(MainActivity.this);
btnGeoTag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String shopid = txtShopCode.getText().toString();
boolean cancel = false;
View focusView = null;
//txtShopCode.setInputType(InputType.TYPE_CLASS_NUMBER);
if (TextUtils.isEmpty(shopid)) {
txtShopCode.setError(getString(R.string.error_field_required));
focusView = txtShopCode;
cancel = true;
}
else {
showProgress(true);
mAuthTask = new GeoTagTask(shopid);
mAuthTask.execute((Void) null);
}
}
});
}
//
// public void btnGeoTag_Click(View v){
//
// }
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
mGeoTagForm.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private final String shopCode;
// private String lat= Double.toString( gps.getLatitude());
// private String lng = Double.toString( gps.getLongitude());
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
// double longitude = location.getLongitude();
private boolean isConnect;
GeoTagTask(String shopId) {
shopCode = shopId;
isConnect = false;
}
#Override
protected Boolean doInBackground(Void... params) {
boolean res = false;
try {
ContentValues nameValuePairs = new ContentValues();
nameValuePairs.put("Id", shopCode);
nameValuePairs.put("lat", lat);
nameValuePairs.put("lng", lng);
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
Log.i("Latitude", lat+"");
Post post = new Post(getApplicationContext());
String result = "";
// isConnect = post.isConnected();
// if(isConnect) {
result = post.doPost(nameValuePairs);
jsonObj = new JSONObject(result);
Log.i("Result", result+"");
if(jsonObj.getInt("success") == 1)
res = true;
// }
} catch (JSONException e) {
e.printStackTrace();
}
return res;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
// Intent intent = new Intent(LoginActivity.this, MainActivity.class);
// intent.putExtra("jsonObj", jsonObj.toString());
// startActivity(intent);
txtShopCode.getText().clear();
txtShopCode.requestFocus();
Toast.makeText(getBaseContext(), "Your shop is geo tagged ", Toast.LENGTH_LONG).show();
} else {
// if(isConnect){
// mPasswordView.setError(getString(R.string.error_incorrect_password));
// mPasswordView.requestFocus();
// }
// else
Toast.makeText(getBaseContext(), R.string.geoTagError, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
#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
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
}
why is google map null? I'm using API in my meta deta
Change you or on create to start with
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Remove additional setContentView calls.
Use getMapAsyc to handle asynchronous map initialization:
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
supportMapFragment.getMapAsync(new OnMapReadyCallback(){
#Override
public void onMapReady(final GoogleMap map) {
map.setMyLocationEnabled(true);
}
});