i have a little problem about my android apps
I'm new in android programing, please help me out
here's my FirstActivity.java code
package com.example.nav;
import android.os.Bundle;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.res.TypedArray;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.content.Intent;
import android.view.Menu;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class FirstActivity extends BaseActivity {
private String[] navMenuTitles;
private TypedArray navMenuIcons;
Button btnGPSShowLocation;
Button btnNWShowLocation;
AppLocationService appLocationService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
set(navMenuTitles, navMenuIcons);
appLocationService = new AppLocationService(FirstActivity.this);
btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);
btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Location gpsLocation = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (GPS): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("GPS");
}
}
});
btnNWShowLocation = (Button) findViewById(R.id.btnNWShowLocation);
btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Location nwLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("NETWORK");
}
}
});
Button btnShow = (Button) findViewById(R.id.btn_show);
btnShow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Location gpsLocation = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
Intent intent = new Intent(getBaseContext(), MapActivity.class);
// Passing latitude and longitude to the MapActiv
intent.putExtra("lat", latitude);
intent.putExtra("lng", longitude);
startActivity(intent);
finish();
}
});
}
public void showSettingsAlert(String provider) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
FirstActivity.this);
alertDialog.setTitle(provider + " SETTINGS");
alertDialog
.setMessage(provider + " is not enabled! Want to go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
FirstActivity.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
here's my MapActivity.java Code
package com.example.nav;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapActivity extends FragmentActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Receiving latitude from MainActivity screen
double latitude = getIntent().getDoubleExtra("lat", 0);
// Receiving longitude from MainActivity screen
double longitude = getIntent().getDoubleExtra("lng", 0);
LatLng position = new LatLng(latitude, longitude);
// Instantiating MarkerOptions class
MarkerOptions options = new MarkerOptions();
// Setting position for the MarkerOptions
options.position(position);
// Setting title for the MarkerOptions
options.title("Position");
// Setting snippet for the MarkerOptions
options.snippet("Latitude:"+latitude+",Longitude:"+longitude);
// Getting Reference to SupportMapFragment of activity_map.xml
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting reference to google map
GoogleMap googleMap = fm.getMap();
// Adding Marker on the Google Map
googleMap.addMarker(options);
// Creating CameraUpdate object for position
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(position);
// Creating CameraUpdate object for zoom
CameraUpdate updateZoom = CameraUpdateFactory.zoomBy(4);
// Updating the camera position to the user input latitude and longitude
googleMap.moveCamera(updatePosition);
// Applying zoom to the marker position
googleMap.animateCamera(updateZoom);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
here's my appLocationService.java
import android.app.Service;
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.os.IBinder;
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#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;
}
}
Here I'm trying to send a latitude and longitude from FirstActivity.java to MapActivity.java, so it can display a point in google map based on the latitude and longitude.
But instead i got an Error
here my Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nav"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<permission
android:name="com.example.nav.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.nav.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".FirstActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity" />
<activity android:name=".MapActivity" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="MY_KEY" />
</application>
here's my logcat
08-01 11:45:52.211: E/AndroidRuntime(2021): java.lang.NullPointerException
08-01 11:45:52.211: E/AndroidRuntime(2021): at com.example.nav.FirstActivity$3.onClick(FirstActivity.java:97)
08-01 11:45:52.211: E/AndroidRuntime(2021): at android.view.View.performClick(View.java:4204)
08-01 11:45:52.211: E/AndroidRuntime(2021): at android.view.View$PerformClick.run(View.java:17355)
08-01 11:45:52.211: E/AndroidRuntime(2021): at android.os.Handler.handleCallback(Handler.java:725)
08-01 11:45:52.211: E/AndroidRuntime(2021): at android.os.Handler.dispatchMessage(Handler.java:92)
08-01 11:45:52.211: E/AndroidRuntime(2021): at android.os.Looper.loop(Looper.java:137)
08-01 11:45:52.211: E/AndroidRuntime(2021): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 11:45:52.211: E/AndroidRuntime(2021): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 11:45:52.211: E/AndroidRuntime(2021): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 11:45:52.211: E/AndroidRuntime(2021): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 11:45:52.211: E/AndroidRuntime(2021): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 11:45:52.211: E/AndroidRuntime(2021): at dalvik.system.NativeStart.main(Native Method)
You get this exception the variable gpsLocation is null. It is supposed to get it's value from appLocationService.
I can see that you created a new appLocationService in
appLocationService = new AppLocationService(FirstActivity.this);
Make sure you have started the service (start service() method).
Also change this:
Button btnShow = (Button) findViewById(R.id.btn_show);
btnShow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Location gpsLocation = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
Intent intent = new Intent(getBaseContext(), MapActivity.class);
// Passing latitude and longitude to the MapActiv
intent.putExtra("lat", latitude);
intent.putExtra("lng", longitude);
startActivity(intent);
finish();
}
});
To this:
Button btnShow = (Button) findViewById(R.id.btn_show);
btnShow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Location gpsLocation = appLocationService
.getLocation(LocationManager.GPS_PROVIDER);
if(gpsLocation==null){
//if no location found create one
gpsLocation =new Location("");
gpsLocation.setLatitude(20.75d);
gpsLocation.setLongitude(44.9d);
}
double latitude = gpsLocation.getLatitude();
double longitude = gpsLocation.getLongitude();
Intent intent = new Intent(getBaseContext(), MapActivity.class);
// Passing latitude and longitude to the MapActiv
intent.putExtra("lat", latitude);
intent.putExtra("lng", longitude);
startActivity(intent);
finish();
}
});
Related
My Problem Is while the app to running. The onClick function should call my position from GPS by longitude, latitude. But the problem is the app crashes when the button is clicked. What is the solution for this? I have tried to follow instructions from older Stack questions, but the error persists.
Here's the debug message:
-----------------------------------------------------------------------------------------------------------------------------------
java.lang.NullPointerException: Attempt to
invoke virtual method 'void
com.google.android.gms.maps.GoogleMap.animateCamera(com.google.android.gms.maps.CameraUpdate)'
on a null object reference
at
com.booleandev.googlfind.MainActivity.onClick(MainActivity.java:97)
-----------------------------------------------------------------------------------------------------------------------------------
public void onClick(View v) {
if (v == koordinat) {
if (latitude != 0 && longitude != 0) {
Toast.makeText(getApplicationContext(), "Latitude : " + latitude + " Longitude : " + longitude, Toast.LENGTH_LONG).show();
}
}
if (v == posisi_user) {
LatLng user = new LatLng(latitude, longitude);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
user, 12));
}
}
this is my full MainActivity.java
package com.booleandev.googlfind;
import android.*;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
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.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity implements LocationListener, OnMapReadyCallback,View.OnClickListener {
GoogleMap googleMap;
double latitude;
double longitude;
Button koordinat;
Button posisi_user;
private final static int MY_PERMISSION_FINE_LOCATION = 101;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
koordinat = (Button) findViewById(R.id.koordinat);
posisi_user = (Button) findViewById(R.id.posisi_user);
koordinat.setOnClickListener(this);
posisi_user.setOnClickListener(this);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
fm.getMapAsync(this);
CekGPS();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// googleMap.setMyLocationEnabled(true);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
}
}
if (latitude != 0 && longitude != 0) {
Toast.makeText(getApplicationContext(), "Latitude : " + latitude + " Longitude : " + longitude, Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
if (v == koordinat) {
if (latitude != 0 && longitude != 0) {
Toast.makeText(getApplicationContext(), "Latitude : " + latitude + " Longitude : " + longitude, Toast.LENGTH_LONG).show();
}
}
if (v == posisi_user) {
LatLng user = new LatLng(latitude, longitude);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
user, 12));
}
}
public void CekGPS() {
try {
/* pengecekan GPS hidup / tidak */
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Info");
builder.setMessage("Anda akan mengaktifkan GPS?");
builder.setPositiveButton("Ya",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
Intent i = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
});
builder.setNegativeButton("Tidak",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
builder.create().show();
}
} catch (Exception e) {
}
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
// menampilkan status google play service
if (status != ConnectionResult.SUCCESS) {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else {
// Google Play Services tersedia
try {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Membuat kriteria untuk penampungan provider
Criteria criteria = new Criteria();
// Mencari provider terbaik
String provider = locationManager.getBestProvider(criteria,
true);
// Mendapatkan lokasi terakhir
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
android.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;
}
locationManager.requestLocationUpdates(provider, 5000, 0, this);
} catch (Exception e) {
}
}
}
#Override
public void onLocationChanged(Location lokasi) {
// TODO Auto-generated method stub
latitude =lokasi.getLatitude();
longitude = lokasi.getLongitude();
}
#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
}
public void onMapReady(GoogleMap googleMap) {
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSION_FINE_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
}
}
else {
Toast.makeText(getApplicationContext(), "GPS TURN OFF", Toast.LENGTH_SHORT).show();
finish();
}
break;
}
}
}
my activity_main.xml too
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/home_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="10"
>
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="9"
android:name="com.google.android.gms.maps.SupportMapFragment"
class="com.google.android.gms.maps.SupportMapFragment"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/koordinat"
style="?android:attr/borderlessButtonStyle"
android:textStyle="bold"
android:layout_height="wrap_content"
android:text="Koordinat User"
android:layout_weight="1"
android:layout_width="0dp" />
<Button
style="?android:attr/borderlessButtonStyle"
android:id="#+id/posisi_user"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Posisi User"/>
</LinearLayout>
</LinearLayout>
the manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.google.android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.permission.ACCESS_COARSE_LOCATION" />
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Secret" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name=".lokasi">
</activity>
<activity android:name=".spalsh">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
You have not initialized the googlemap variable in on map ready
Like this.googleMap=googleMap;
public void onMapReady(GoogleMap googleMap) {
this.googleMap=googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setTrafficEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
}
TRY THIS
I am trying to create an android program to get the location
but unfortunately its throwing the exception as unfortunately APP is stopped
Can you suggest me please .code is the following
package com.example.ngo;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity
implements OnClickListener {
private LocationManager locationMangaer=null;
private LocationListener locationListener=null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to"+
" see the changes in coordinates."+"\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager
.GPS_PROVIDER, 5000, 10,locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----Method to Check GPS is enable or disable ----- */
#SuppressLint("NewApi") private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext()
.getContentResolver();
boolean gpsStatus = Settings.Secure
.isLocationProviderEnabled(contentResolver,
LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " +
loc.getLatitude()+ " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +
"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
#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
}
}
}
When I press the button btnlocation it should go to the Mapsactivity
but it is giving me the error:
java.lang.NoClassDefFoundError
I also added MapsActivity in manifest as usual .. .but why this error? I need the solution.Can any one help me please...
package com.mamun.tasktest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
public class FragmentB extends Fragment implements OnClickListener {
private Button btnLocation;
private LocationManager manager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_b, null, false);
btnLocation = (Button) view.findViewById(R.id.btnLocation);
btnLocation.setOnClickListener(this);
manager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("GPS is currently disabled");
builder.setMessage("Please enable GPS for better view of your location.\nWould you like to change these settings now?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
getActivity();
}
});
builder.create().show();
}
return view;
}
#Override
public void onClick(View v) {
if(isMapAvailalble()){
/////////////////////////////
/*
// */
//////////////////////////
Intent in = new Intent(getActivity(),MapsActivity.class);
startActivity(in);
}
}
/*Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); intent.putExtra("enabled", false);
sendBroadcast(intent);*/
//if googleplayservis or play store is not available/updated or user recoverable problem occured.
public boolean isMapAvailalble()
{
// to test if there is no googleplayservise
//int resultcode=ConnectionResult.SERVICE_MISSING;
int resultcode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if(ConnectionResult.SUCCESS==resultcode)
{
return true;
}
else if(GooglePlayServicesUtil.isUserRecoverableError(resultcode))
{
Dialog d = GooglePlayServicesUtil.getErrorDialog(resultcode, getActivity(), 1);
d.show();
}
else
{
Toast.makeText(getActivity()," Google Map API is not supported in your device",Toast.LENGTH_LONG).show();
}
return false;
}
/*public void turnGPSOn()
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
((Context) this.ctx).sendBroadcast(intent);
#SuppressWarnings("deprecation")
String provider = Settings.Secure.getString(((Context) ctx).getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
((Context) this.ctx).sendBroadcast(poke);
}*/
}
Manifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mamun.tasktest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.mamun.tasktest.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-library android:name="com.google.android.maps"/>
<permission
android:name="com.mamun.tasktest.permission.MAPS_RECEIVE"
android:protectionLevel="signature" >
</permission>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.mamun.tasktest.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCgGng3iaqbTxJ3B_lYemZBEqXOonUtFEI" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name="MapsActivity"></activity>
</application>
</manifest>
MapsActivity
package com.mamun.tasktest;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
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.MapView;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.MapActivity;
public class MapsActivity<GeoPoint, OverlayItem> extends MapActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
MapView mapView;
com.google.android.maps.GeoPoint p;
private LocationManager manager;
private TextView tvAddress;
private Button btnSearch;
private EditText etSearch;
private LocationClient locationClient;
private GoogleMap googleMap;
private MapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
tvAddress = (TextView) findViewById(R.id.tvaddress);
btnSearch = (Button) findViewById(R.id.btnSearch);
etSearch = (EditText) findViewById(R.id.etSearch);
mapFragment = (MapFragment) getFragmentManager().findFragmentById(
R.id.maps);
googleMap = mapFragment.getMap();
locationClient = new LocationClient(this, this, this);
}
public void onSearch(View v) {
// Getting user input location
String location = etSearch.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationClient.connect();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationClient.disconnect();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
try {
Location currentLocation = locationClient.getLastLocation();
double lat = currentLocation.getLatitude();
double lng = currentLocation.getLongitude();
// txtLocation.setText(lat + ", " + lng);
Geocoder geocoder = new Geocoder(this);
ArrayList<Address> address = (ArrayList<Address>) geocoder
.getFromLocation(currentLocation.getLatitude(),
currentLocation.getLongitude(), 5);
Address addr = address.get(0);
String currentAddress = (addr.getAddressLine(0) + "-"
+ addr.getAdminArea() + "-" + addr.getLocality() + "-"
+ addr.getPostalCode() + "-" + addr.getCountryCode());
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(lat, lng));
options.title(currentAddress);
options.snippet("Current location");
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
if (googleMap != null) {
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(lat, lng), 14.0f));
googleMap.addMarker(options);
} else {
Toast.makeText(getApplicationContext(), "Map is null",
Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
// An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends
AsyncTask<String, Void, ArrayList<Address>> {
#Override
protected ArrayList<Address> doInBackground(String... locationName) {
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
ArrayList<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = (ArrayList<Address>) geocoder.getFromLocationName(
locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
#Override
protected void onPostExecute(ArrayList<Address> addresses) {
if (addresses == null || addresses.size() == 0) {
Toast.makeText(getBaseContext(), "No Location found",
Toast.LENGTH_SHORT).show();
return;
}
// Clears all the existing markers on the map
googleMap.clear();
// Adding Markers on Google Map for each matching address
for (int i = 0; i < addresses.size(); i++) {
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
LatLng latLng;
latLng = new LatLng(address.getLatitude(),
address.getLongitude());
String addressText = String.format(
"%s, %s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address
.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
// markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(addressText);
googleMap.addMarker(markerOptions);
// Locate the first location
if (i == 0)
googleMap.animateCamera(CameraUpdateFactory
.newLatLng(latLng));
}
}
}
class MapOverlay extends com.google.android.maps.Overlay {
#Override
public void draw(Canvas canvas, com.google.android.maps.MapView mapView,
boolean shadow) {
// TODO Auto-generated method stub
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
}
#Override
public boolean onTouchEvent(MotionEvent e,
com.google.android.maps.MapView mapView) {
// TODO Auto-generated method stub
if (e.getAction() == 1) {
com.google.android.maps.GeoPoint p = mapView.getProjection().fromPixels(
(int) e.getX(), (int) e.getY());
Toast.makeText(
getBaseContext(),
"Lat: " + p.getLatitudeE6() / 1E6 + ", Lon: "
+ p.getLongitudeE6() / 1E6, Toast.LENGTH_SHORT)
.show();
}
return false;
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Add Activity into your manifest.xml because you need to give all path if your Activity located into different package.
<activity
android:name="com.mamun.tasktest.MapsActivity"
android:label="MapActivity" >
</activity>
And/or is your Activity belong to the same package then add simply
<activity android:name=".MapsActivity"></activity>
For more information go to:http://developer.android.com/guide/topics/manifest/manifest-intro.html
This is incorrect:
<activity android:name="MapsActivity"></activity>
You need to give full or relative path like this:
<activity android:name="com.mamun.tasktest.MapsActivity"></activity>
or
<activity android:name=".MapsActivity"></activity>
Replace your this tag in manifest
<activity android:name="MapsActivity"></activity>
by :
<activity android:name=".MapsActivity"></activity>
you should specify your full package name while declaring your activity into manifets.
See this link for reference:-
Add a new activity to the AndroidManifest?
You just forget to place a DOt (.) before MapsActivity. So, without that Dot (.) your class path looks like...
com.mamun.tasktestMapsActivity.java
But, it should be as....
com.mamun.tasktest.MapsActivity.java
Now, change this line of your Manifest...
<activity android:name="MapsActivity"></activity>
to...
<activity android:name=".MapsActivity"></activity>
I got the solution....The line "" should be inside application not inside directly on manifest.Like as below....
i am trying google maps api on my android phone via following code. My app locating my phone and working great but gps notification icon not blinking. How can i blink gps icon when locating my phone.
Thanks For Replies.
Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
And The Code :
import java.util.List;
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.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.EditText;
import android.widget.Toast;
public class main extends MapActivity {
MapController mControl;
GeoPoint geoP;
MapView mapV;
MyLocationOverlay compass;
EditText etext;
String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etext = (EditText) findViewById(R.id.latLong);
mapV = (MapView) findViewById(R.id.mapView);
mapV.displayZoomControls(true);
mapV.setBuiltInZoomControls(true);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean enable = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enable) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
Criteria criteria = new Criteria();
//criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Double lat = location.getLatitude() * 1E6;
Double longi = location.getLongitude() * 1E6;
geoP = new GeoPoint(lat.intValue(), longi.intValue());
List<Overlay> mapOverlays = mapV.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
compass = new MyLocationOverlay(this, mapV);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
OverlayItem overlayitem = new OverlayItem(geoP, "Hola, Mundo!","I'm in Mexico City!");
itemizedoverlay.addOverlay(overlayitem);
mapV.getOverlays().add(compass);
mapOverlays.add(itemizedoverlay);
mControl = mapV.getController();
mControl.animateTo(geoP);
mControl.setZoom(5);
mControl.setCenter(geoP);
locationManager.requestLocationUpdates(provider, 0, 0,
new LocationListener() {
public void onStatusChanged(String provider, int status,
Bundle extras) {
if (status == LocationProvider.AVAILABLE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.AVAILABLE",
Toast.LENGTH_SHORT).show();
} else if (status == LocationProvider.TEMPORARILY_UNAVAILABLE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.TEMPORARILY_UNAVAILABLE",
Toast.LENGTH_SHORT).show();
} else if (status == LocationProvider.OUT_OF_SERVICE) {
Toast.makeText(getApplicationContext(),
"LocationProvider.OUT_OF_SERVICE",
Toast.LENGTH_SHORT).show();
}
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
public void onLocationChanged(Location location) {
Toast.makeText(getApplicationContext(),
"Location Changed", Toast.LENGTH_SHORT).show();
}
});
//etext.setText(String.valueOf(lat) + "," + String.valueOf(longi));
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
compass.disableCompass();
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
compass.enableCompass();
}
protected boolean isRouteDisplayed() {
return false;
}
t0mm13b, working on my handset but GPS notification icon not blinking. Virtual Device means Emulator. I solved problem.
Code :
package com.yunusoksuz.gmapstest;
import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class YnsmapsActivity extends Activity implements LocationListener {
/** Called when the activity is first created. */
private LocationManager locationManager;
private Location location;
private String provider;
private Double lat, longi;
private Criteria criteria;
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv1);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
public void onLocationChanged(Location location) {
Toast.makeText(
this,
"Lat : " + location.getLatitude() + " LONG : "
+ location.getLongitude(), Toast.LENGTH_SHORT).show();
tv.setText("Lat : " + location.getLatitude() + " LONG : "
+ location.getLongitude());
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationManager.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
}
}
Now gps notification blinking.
package gpstest.example.com;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.views.overlay.MyLocationOverlay;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import android.content.Context;
import android.graphics.Paint;
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class gpstestActivity extends Activity
{
public LocationManager mlocManager;
public LocationListener mlocListener;
public boolean isFirstRun=true;
protected final Paint mPaint = new Paint();
private MapView myMap;
private MyLocationOverlay myLocOverlay;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gpsEnable();
setMap();
initMyLocation();
}
public void setMap(){
MapView map = (MapView) findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
map.getController().setZoom(16);
map.getController().setCenter(new GeoPoint(30266000, -97739000));
}
private void initMyLocation() {
myLocOverlay = new MyLocationOverlay(this, myMap);
myLocOverlay.enableMyLocation();
myMap.getOverlays().add(myLocOverlay);
}
public void gpsEnable (){
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 10, 50, mlocListener);
}
public void gpsDisable(){
mlocManager.removeUpdates(mlocListener);}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
double longi=loc.getLongitude();
double lati=loc.getLatitude();
MapView map = (MapView) findViewById(R.id.map);
map.getController().setCenter(new GeoPoint(lati, longi));
String Text="My current location is: " +
"Latitud = " + loc.getLatitude() +
"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
//initMyLocation();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
"Gps Disabled",
Toast.LENGTH_SHORT ).show();
mlocManager.removeUpdates(mlocListener);
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
"Gps Enabled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Toast.makeText( getApplicationContext(),
"Status changed",
Toast.LENGTH_SHORT).show();
}
}/* End of Class MyLocationListener */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.beenden: mlocManager.removeUpdates(mlocListener);}
return true;
}
protected void onPause(){
Toast.makeText( getApplicationContext(),
"On Pause",
Toast.LENGTH_SHORT).show();
gpsDisable();
isFirstRun=false;
super.onPause();
}
protected void onDestroy(){
Toast.makeText( getApplicationContext(),
"Destroyed",
Toast.LENGTH_SHORT).show();
gpsDisable();
super.onDestroy();
}
protected void onResume(){
if (isFirstRun==false){gpsEnable();}
Toast.makeText( getApplicationContext(),
"Resumed",
Toast.LENGTH_SHORT).show();
super.onResume();
}
}/* Ende Activity */
Whenever I call initMyLocation, the app crashes (bot on emulator and device). Same happens when I try to implement a MiniMap. I do exactly the same as in the SampleExtensive example from the Osmdroid repository. What am I doing wrong?
My AndroidManifest.xml is giving all required permissions I think
<?xml version="1.0" encoding="utf-8"?>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".gpstestActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
In your setMap(), you never set
myMap = map;
So in initMyLocation, you are passing null for the pMapView parameter.
to use location you must have the following in your AndroidManifest.xml :
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>