FATAL EXCEPTION: main Android - java

Hi i am new to android development. i am trying to get the users coordinates using the GPS, i get the error saying FATAL EXCEPTION: main Android.
here is my code
package lk.adspace.finetech;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class Main extends Activity implements LocationListener {
TextView viewlocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,1.0f, this);
boolean isGPS = locationManager.isProviderEnabled (LocationManager.GPS_PROVIDER);
if (isGPS){
}else{
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
String locationProvider = LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(locationProvider, 400, 1, this);
// Location loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
viewlocation = (TextView) findViewById(R.id.location);
viewlocation.setText("My Current location \n Latitude = "+ loc.getLatitude()+" \n Longitude = "+ loc.getLongitude());
}
...
}
This the error i get
08-20 12:08:37.436: E/AndroidRuntime(25888): FATAL EXCEPTION: main
08-20 12:08:37.436: E/AndroidRuntime(25888): java.lang.RuntimeException: Unable to start activity ComponentInfo{lk.adspace.finetech/lk.adspace.finetech.Main}: java.lang.NullPointerException
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.ActivityThread.access$600(ActivityThread.java:162)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.os.Handler.dispatchMessage(Handler.java:107)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.os.Looper.loop(Looper.java:194)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.ActivityThread.main(ActivityThread.java:5371)
08-20 12:08:37.436: E/AndroidRuntime(25888): at java.lang.reflect.Method.invokeNative(Native Method)
08-20 12:08:37.436: E/AndroidRuntime(25888): at java.lang.reflect.Method.invoke(Method.java:525)
08-20 12:08:37.436: E/AndroidRuntime(25888): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
08-20 12:08:37.436: E/AndroidRuntime(25888): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
08-20 12:08:37.436: E/AndroidRuntime(25888): at dalvik.system.NativeStart.main(Native Method)
08-20 12:08:37.436: E/AndroidRuntime(25888): Caused by: java.lang.NullPointerException
08-20 12:08:37.436: E/AndroidRuntime(25888): at lk.adspace.finetech.Main.onCreate(Main.java:68)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.Activity.performCreate(Activity.java:5122)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
08-20 12:08:37.436: E/AndroidRuntime(25888): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
08-20 12:08:37.436: E/AndroidRuntime(25888): ... 11 more
can anyone help me to fix this problem. tnx.

You are checking if GPS is enabled as a boolean isGPS. Move your code to within the block. Probably, the exception is thrown when the GPS provider is not enabled via settings. Your code should probably be as below:
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,1.0f, this);
boolean isGPS = locationManager.isProviderEnabled (LocationManager.GPS_PROVIDER);
if (isGPS){
// -------- IF GPS IS ENABLED, GET COORDINATES AND DISPLAY TO USER ------
String locationProvider = LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(locationProvider, 400, 1, this);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) // <---- This line can be included to avoid null pointer exception in case you are not able to get the coordinates.
{
viewlocation = (TextView) findViewById(R.id.location);
viewlocation.setText("My Current location \n Latitude = "+ loc.getLatitude()+" \n Longitude = "+ loc.getLongitude());
}
}else{
// --------IF GPS NOT ENABLED, THEN MOVE TO SETTINGS SCREEN TO HELP USER TO ENABLE GPS.
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}

I think you should check loc is null or not;
if (loc != null) {
viewlocation = (TextView) findViewById(R.id.location);
viewlocation.setText("My Current location \n Latitude = "+ loc.getLatitude()+" \n Longitude = "+ loc.getLongitude());
}

There is null pointer exception at Line #68
8-20 12:08:37.436: E/AndroidRuntime(25888): at lk.adspace.finetech.Main.onCreate(Main.java:68)
I think loc below is returned as null. Please check.
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
While accessing loc.getLatitude(), its throwing exception. You can add null check or fetch location from different provider. Also, check if GPS provider is disabled currently.

Related

Can not retrieve location, app crashes

I have two classes.
MainActivity:
package ytu.ytu1;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button gpsBtn;
private TextView gpsTxt;
private LocationManager locMngr;
private LocationListener locLstnr;
GPSTracker gps;
double lot,lat;
String txt;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lat=gps.getLocation().getLongitude();
lot=gps.getLocation().getLatitude();
txt="longti "+lat + "latit " +lot;
gpsTxt = (TextView) findViewById(R.id.gpsTxt);
gpsTxt.setText("Coordinates: ");
gpsTxt.append(txt);
Toast.makeText(MainActivity.this,txt,
Toast.LENGTH_LONG).show();
}}
GPSTracker.java from here
http://pastie.org/9300205
only permissions were changed, because i am using this on android kitkat tablet.
package ytu.ytu1;
/**
* Created by mia on 11/28/2015.
*/
import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
private TextView txt;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 5000; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void StoprequestUpdates() {
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// 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 Activity#requestPermissions for more details.
if (isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isNetworkEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
return;
} else {
}
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
// if GPS Enabled get lat/long using GPS Services
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
if (isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isNetworkEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
locationManager.removeUpdates(GPSTracker.this);return;}
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
*
*
*
*
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog
.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
this.location = location;
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
I can not even debug, as soon as it starts, it crashes without showing any view.
logcat:
11-28 16:51:19.541 9413-9413/? D/dalvikvm: Late-enabling CheckJNI
11-28 16:51:19.591 9413-9413/? D/ActivityThread: handleBindApplication:ytu.ytu1
11-28 16:51:19.621 9413-9413/ytu.ytu1 W/ApplicationPackageManager: getCSCPackageItemText()
11-28 16:51:19.631 9413-9413/ytu.ytu1 D/DisplayManager: DisplayManager()
11-28 16:51:19.641 9413-9413/ytu.ytu1 W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
11-28 16:51:19.641 9413-9413/ytu.ytu1 I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onSearchRequested
11-28 16:51:19.641 9413-9413/ytu.ytu1 W/dalvikvm: VFY: unable to resolve interface method 17904: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
11-28 16:51:19.641 9413-9413/ytu.ytu1 D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-28 16:51:19.641 9413-9413/ytu.ytu1 I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onWindowStartingActionMode
11-28 16:51:19.641 9413-9413/ytu.ytu1 W/dalvikvm: VFY: unable to resolve interface method 17908: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
11-28 16:51:19.641 9413-9413/ytu.ytu1 D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-28 16:51:19.661 9413-9413/ytu.ytu1 D/AndroidRuntime: Shutting down VM
11-28 16:51:19.661 9413-9413/ytu.ytu1 W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x416adbc0)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: FATAL EXCEPTION: main
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: Process: ytu.ytu1, PID: 9413
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{ytu.ytu1/ytu.ytu1.MainActivity}: java.lang.NullPointerException
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2429)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.access$800(ActivityThread.java:166)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.os.Looper.loop(Looper.java:136)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5584)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: Caused by: java.lang.NullPointerException
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at ytu.ytu1.MainActivity.onCreate(MainActivity.java:44)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:5447)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.access$800(ActivityThread.java:166) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.os.Looper.loop(Looper.java:136) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5584) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084) 
11-28 16:51:19.661 9413-9413/ytu.ytu1 E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method) 
I am using on android studio and i did not change the original code so much. I dont understand why it wont start.
Try something like this:
GPSTracker gps = new GPSTracker(this);
also check this tutorial: http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/

Fatal error in Fragment class

I'M developing on a finding nearby place on GooGle map v2.project contains no error but there is unable to find activity error in Logcat.
so i think the problem is in oncreate() method whiche i set Adapter.
could you cheek my code please.
MainActivity.java
public class MainActivity extends FragmentActivity implements LocationListener{
GoogleMap mGoogleMap;
Spinner mSprPlaceType;
String[] mPlaceType=null;
String[] mPlaceTypeName=null;
double mLatitude=0;
double mLongitude=0;
#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);
// 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=5000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=9C:6F:F6:C2:68:9F:EF:26:42:3F:6E:1F:79:8C:18:B3:0E:16:11:A9");
// 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;
// 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();
// 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);
// Placing a marker on the touched position
mGoogleMap.addMarker(markerOptions);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
Logcat :
07-29 07:05:55.531: E/AndroidRuntime(847): java.lang.RuntimeException: Unable to start activity ComponentInfo{in.wptrafficanalyzer.locationnearby/in.wptrafficanalyzer.locationnearby.MainActivity}: android.view.InflateException: Binary XML file line #21: Error inflating class fragment
07-29 07:05:55.531: E/AndroidRuntime(847): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.os.Handler.dispatchMessage(Handler.java:99)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.os.Looper.loop(Looper.java:137)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.app.ActivityThread.main(ActivityThread.java:5103)
07-29 07:05:55.531: E/AndroidRuntime(847): at java.lang.reflect.Method.invokeNative(Native Method)
07-29 07:05:55.531: E/AndroidRuntime(847): at java.lang.reflect.Method.invoke(Method.java:525)
07-29 07:05:55.531: E/AndroidRuntime(847): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
07-29 07:05:55.531: E/AndroidRuntime(847): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-29 07:05:55.531: E/AndroidRuntime(847): at dalvik.system.NativeStart.main(Native Method)
07-29 07:05:55.531: E/AndroidRuntime(847): Caused by: android.view.InflateException: Binary XML file line #21: Error inflating class fragment
07-29 07:05:55.531: E/AndroidRuntime(847): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
07-29 07:05:55.531: E/AndroidRuntime(847): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:267)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.app.Activity.setContentView(Activity.java:1895)
07-29 07:05:55.531: E/AndroidRuntime(847): at in.wptrafficanalyzer.locationnearby.MainActivity.onCreate(MainActivity.java:56)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.app.Activity.performCreate(Activity.java:5133)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
07-29 07:05:55.531: E/AndroidRuntime(847): ... 11 more
07-29 07:05:55.531: E/AndroidRuntime(847): Caused by: java.lang.IllegalStateException: The meta-data tag in your app's AndroidManifest.xml does not have the right value. Expected 7571000 but found 0. You must have the following declaration within the <application> element: <meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
07-29 07:05:55.531: E/AndroidRuntime(847): at com.google.android.gms.common.GooglePlayServicesUtil.zzaa(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847): at com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847): at com.google.android.gms.maps.internal.zzy.zzaz(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847): at com.google.android.gms.maps.internal.zzy.zzay(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847): at com.google.android.gms.maps.MapsInitializer.initialize(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847): at com.google.android.gms.maps.SupportMapFragment$zzb.zzvu(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847): at com.google.android.gms.maps.SupportMapFragment$zzb.zza(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847): at com.google.android.gms.dynamic.zza.zza(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847): at com.google.android.gms.dynamic.zza.onInflate(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847): at com.google.android.gms.maps.SupportMapFragment.onInflate(Unknown Source)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:279)
07-29 07:05:55.531: E/AndroidRuntime(847): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)
I think you should have to change
SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
to
SupportMapFragment fragment = ((SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map));
For more info please look at this answer...
you should add these line in your layout file
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
I think you r using com.google.android.gms.maps.MapFragment.

Runtime errors when method is invoked?

I'm having some issues when I am running my method. How can I get it working so my mock locations will work on my actual device. (Ps. I've included permissions).
This provides a null pointer exception and I am not to sure why?
Method:
private void setMockLocation() {
{
Context context = null;
LocationManager locationManager = (LocationManager)context.getSystemService( Context.LOCATION_SERVICE );
Criteria criteria = new Criteria();
criteria.setAccuracy( Criteria.ACCURACY_COARSE );
String provider = locationManager.getBestProvider( criteria, true );
if ( provider == null ) {
Log.e( TAG, "No location provider found!" );
return;
}
locationManager.getLastKnownLocation(provider);
Location newLocation = new Location(LocationManager.GPS_PROVIDER);
newLocation.setLatitude(55.9500);
newLocation.setLongitude(3.1833);
newLocation.setAccuracy(500);
mLocationManager.setTestProviderEnabled
(
LocationManager.GPS_PROVIDER,
true
);
mLocationManager.setTestProviderStatus
(
LocationManager.GPS_PROVIDER,
LocationProvider.AVAILABLE,
null,
System.currentTimeMillis()
);
mLocationManager.setTestProviderLocation
(
LocationManager.GPS_PROVIDER,
newLocation
);
}
}
Stack Trace:
05-10 18:50:46.218 14398-14398/com.example.ankhit.saveme E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.ankhit.saveme.UserLocation.setMockLocation(UserLocation.java:220)
at com.example.ankhit.saveme.UserLocation.access$000(UserLocation.java:42)
at com.example.ankhit.saveme.UserLocation$4.onClick(UserLocation.java:175)
at android.view.View.performClick(View.java:4439)
at android.view.View$PerformClick.run(View.java:18398)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5299)
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:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
However, when I add the code below to Context context code shown above I get a 'GPS Provider Unknown' Error
LocationManager locationManager = (LocationManager)context.getSystemService( Context.LOCATION_SERVICE );
Criteria criteria = new Criteria();
criteria.setAccuracy( Criteria.ACCURACY_COARSE );
String provider = locationManager.getBestProvider( criteria, true );
if ( provider == null ) {
Log.e( TAG, "No location provider found!" );
return;
}
lastLocation = locationManager.getLastKnownLocation(provider);
StackTrace:
05-10 18:54:37.395 15159-15159/com.example.ankhit.saveme E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalArgumentException: Provider "gps" unknown
at android.os.Parcel.readException(Parcel.java:1429)
at android.os.Parcel.readException(Parcel.java:1379)
at android.location.ILocationManager$Stub$Proxy.removeTestProvider(ILocationManager.java:956)
at android.location.LocationManager.removeTestProvider(LocationManager.java:1194)
at com.example.ankhit.saveme.UserLocation.setMockLocation(UserLocation.java:218)
at com.example.ankhit.saveme.UserLocation.access$000(UserLocation.java:42)
at com.example.ankhit.saveme.UserLocation$4.onClick(UserLocation.java:175)
at android.view.View.performClick(View.java:4439)
at android.view.View$PerformClick.run(View.java:18398)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5299)
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:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Any Ideas?
The NullPointerException should come from
Context context = null;
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
because context is null and you invoke a method on it.

Getting Noclassdeffounderror on working with Google places API android

I am working on a tutorial found on this link:
http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/
I am getting the following error on clicking the button:
08-13 12:28:03.226: E/AndroidRuntime(9180): FATAL EXCEPTION: main
08-13 12:28:03.226: E/AndroidRuntime(9180): java.lang.NoClassDefFoundError: com.androidhive.googleplacesandmaps.PlacesMapActivity
08-13 12:28:03.226: E/AndroidRuntime(9180): at com.androidhive.googleplacesandmaps.MainActivity$1.onClick(MainActivity.java:110)
08-13 12:28:03.226: E/AndroidRuntime(9180): at android.view.View.performClick(View.java:2538)
08-13 12:28:03.226: E/AndroidRuntime(9180): at android.view.View$PerformClick.run(View.java:9152)
08-13 12:28:03.226: E/AndroidRuntime(9180): at android.os.Handler.handleCallback(Handler.java:587)
08-13 12:28:03.226: E/AndroidRuntime(9180): at android.os.Handler.dispatchMessage(Handler.java:92)
08-13 12:28:03.226: E/AndroidRuntime(9180): at android.os.Looper.loop(Looper.java:130)
08-13 12:28:03.226: E/AndroidRuntime(9180): at android.app.ActivityThread.main(ActivityThread.java:3689)
08-13 12:28:03.226: E/AndroidRuntime(9180): at java.lang.reflect.Method.invokeNative(Native Method)
08-13 12:28:03.226: E/AndroidRuntime(9180): at java.lang.reflect.Method.invoke(Method.java:507)
08-13 12:28:03.226: E/AndroidRuntime(9180): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
08-13 12:28:03.226: E/AndroidRuntime(9180): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
08-13 12:28:03.226: E/AndroidRuntime(9180): at dalvik.system.NativeStart.main(Native Method)
08-13 12:28:03.226: E/AndroidRuntime(9180): Caused by: java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation
08-13 12:28:03.226: E/AndroidRuntime(9180): at dalvik.system.DexFile.defineClass(Native Method)
08-13 12:28:03.226: E/AndroidRuntime(9180): at dalvik.system.DexFile.loadClassBinaryName(DexFile.java:207)
08-13 12:28:03.226: E/AndroidRuntime(9180): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:200)
08-13 12:28:03.226: E/AndroidRuntime(9180): at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
08-13 12:28:03.226: E/AndroidRuntime(9180): at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
08-13 12:28:03.226: E/AndroidRuntime(9180): ... 12 more
The placesmapactivity.java class is shown below:
package com.androidhive.googleplacesandmaps;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class PlacesMapActivity extends MapActivity {
// Nearest places
PlacesList nearPlaces;
// Map view
MapView mapView;
// Map overlay items
List<Overlay> mapOverlays;
AddItemizedOverlay itemizedOverlay;
GeoPoint geoPoint;
// Map controllers
MapController mc;
double latitude;
double longitude;
OverlayItem overlayitem;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_places);
// Getting intent data
Intent i = getIntent();
// Users current geo location
String user_latitude = i.getStringExtra("user_latitude");
String user_longitude = i.getStringExtra("user_longitude");
// Nearplaces list
nearPlaces = (PlacesList) i.getSerializableExtra("near_places");
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
// Geopoint to place on map
geoPoint = new GeoPoint((int) (Double.parseDouble(user_latitude) * 1E6),
(int) (Double.parseDouble(user_longitude) * 1E6));
// Drawable marker icon
Drawable drawable_user = this.getResources()
.getDrawable(R.drawable.mark_red);
itemizedOverlay = new AddItemizedOverlay(drawable_user, this);
// Map overlay item
overlayitem = new OverlayItem(geoPoint, "Your Location",
"That is you!");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay.populateNow();
// Drawable marker icon
Drawable drawable = this.getResources()
.getDrawable(R.drawable.mark_blue);
itemizedOverlay = new AddItemizedOverlay(drawable, this);
mc = mapView.getController();
// These values are used to get map boundary area
// The area where you can see all the markers on screen
int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;
// check for null in case it is null
if (nearPlaces.results != null) {
// loop through all the places
for (Place place : nearPlaces.results) {
latitude = place.geometry.location.lat; // latitude
longitude = place.geometry.location.lng; // longitude
// Geopoint to place on map
geoPoint = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
// Map overlay item
overlayitem = new OverlayItem(geoPoint, place.name,
place.vicinity);
itemizedOverlay.addOverlay(overlayitem);
// calculating map boundary area
minLat = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
maxLat = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
}
mapOverlays.add(itemizedOverlay);
// showing all overlay items
itemizedOverlay.populateNow();
}
// Adjusting the zoom level so that you can see all the markers on map
mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
// Showing the center of the map
mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
mapView.postInvalidate();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
The button click code is shown below:
btnShowOnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(MainActivity.this,
PlacesMapActivity.class);
// Sending user current geo location
i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
// passing near places to map activity
i.putExtra("near_places", nearPlaces);
// staring activity
startActivity(i);
}
});
}

java.lang.NullPointerException:com.google.android.gms.maps.GoogleMap.moveCamera

I am currently working on the new Google Maps Android API v2.
My MapActivity class is working with my Samsung galaxy s3 ans s2 with the code below:
However, there are some particular devices are not working such as: GT-S5830i
class MapActivity extends FragmentActivity implements OnMapClickListener, OnMapLongClickListener, OnMarkerClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
tvLocInfo = (TextView)findViewById(R.id.locinfo);
android.support.v4.app.FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment myMapFragment = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
ArrayList<Cooridnates> cooridnatesList = MainActivity.getList();
for(int i=0;i<cooridnatesList.size();i++)
{
//Toast.makeText(MapActivity.this, "SIZE : " + " " + cooridnatesList.size(), Toast.LENGTH_LONG).show();
LatLng point = new LatLng(cooridnatesList.get(i).getLat(),cooridnatesList.get(i).getLon());
tvLocInfo.setText("markers added");
myMap.addMarker(new MarkerOptions().position(point).title(point.toString()));
center=CameraUpdateFactory.newLatLng(point);
}
CameraUpdate zoom=CameraUpdateFactory.zoomTo(16);
myMap.moveCamera(center);
myMap.animateCamera(zoom);
myMap.setOnMapClickListener(this);
myMap.setOnMarkerClickListener(this);
markerClicked = false;
}
For some reason, I am getting this error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.coldice.plotfinder/com.coldice.plotfinder.MapActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
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:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.google.android.gms.maps.GoogleMap.moveCamera(Unknown Source)
at com.coldice.plotfinder.MapActivity.onCreate(MapActivity.java:70)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
... 11 more
You function MainActivity.getList() probably returned an empty list, so for loop doesn't execute center=CameraUpdateFactory.newLatLng(point);.
it seems center is null in this >> myMap.moveCamera(center);, make an appropriate check on this variable before passing it in moveCamera method.
It seems problem is here. center might have null value, So to get proper explanation debug your application.
center is initialzed here.
center=CameraUpdateFactory.newLatLng(point);
It might assign null in center.
myMap.moveCamera(center); <<<PROBLEM is here
if(center != null )
myMap.moveCamera(center);

Categories

Resources