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....
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 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();
}
});
In Google Maps, I'm dropping a pin on user's current location but now I want to give another functionality to user that he can drag that pin manually and drop anywhere on the map, also by the time he drops the pin manually I can receive a callback which gives me the Longitude and Latitude of that position where user drops that pin.
If you can give me some examples it will be greatly appreciable.
In the last few days I finally found how to implement those functions you described and because there was no answer in this question, I decided to post what I found even though there has been a long time since you asked and you may found another answer by yourself.
So, I used the code of this git. I managed to do all that you want except the callback that I didn't try it in that way. I am getting the position of the pin after pressing a button.
There is no need to post my AndroidManifest because I read that you had no problem with displaying your location, so the permissions needed were fine.
The only thing that was required to do, was to create an activity named MapsActivity.
This is the whole content of it:
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.model.*;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import common.logger.Log;
public class MapsActivity extends Activity implements
OnMapReadyCallback, GoogleMap.OnInfoWindowClickListener,
GoogleMap.OnMarkerDragListener {
LatLng position = new LatLng(34.6767, 33.04455);
final Marker marker_final = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.
map);
mapFragment.getMapAsync(this);
ImageButton returnback = (ImageButton)findViewById(R.id.returnback);
returnback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MapsActivity.this.getApplicationContext(), position.latitude + ":" + position.longitude, Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onMapReady(GoogleMap map) {
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
map.animateCamera(zoom);
map.addMarker(new MarkerOptions()
.title("Shop")
.snippet("Is this the right location?")
.position(position))
.setDraggable(true);
// map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
map.setOnInfoWindowClickListener(this);
map.setOnMarkerDragListener(this);
}
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(this, marker.getTitle(), Toast.LENGTH_LONG).show();
}
#Override
public void onMarkerDragStart(Marker marker) {
LatLng position0 = marker.getPosition();
Log.d(getClass().getSimpleName(), String.format("Drag from %f:%f",
position0.latitude,
position0.longitude));
}
#Override
public void onMarkerDrag(Marker marker) {
LatLng position0 = marker.getPosition();
Log.d(getClass().getSimpleName(),
String.format("Dragging to %f:%f", position0.latitude,
position0.longitude));
}
#Override
public void onMarkerDragEnd(Marker marker) {
position = marker.getPosition();
Log.d(getClass().getSimpleName(), String.format("Dragged to %f:%f",
position.latitude,
position.longitude));
}
}
This is my activity_maps.xml layout (I've also added an edit text, but there is no need to use it):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
android:background="#ecf0f1">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/scrollView3" >
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:weightSum="1"
android:layout_height="wrap_content">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.9"
android:id="#+id/locationsearch" />
<ImageButton
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/search"
android:layout_weight="0.1"
android:background="#drawable/search" />
</LinearLayout>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="405dp"
android:name="com.google.android.gms.maps.MapFragment"/>
<ImageButton
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/returnback"
android:background="#drawable/less" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Refer Below links where you can find samples from Commons guy
Sample
SO question
Hi Use the below code.
you will get the dropped pin position.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
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.OverlayItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class rescue extends MapActivity {
private LocationManager myLocationManager;
private LocationListener myLocationListener;
private MapView myMapView;
private MapController myMapController;
private String provider;
private MyLocationOverlay me=null;
private int defaultLat =(int)(51.51216124955517);
private int defaultLong =(int)(-0.1373291015625);
private GeoPoint defaultGeoPint = new GeoPoint(defaultLat,defaultLong);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rescue);
setCurrentLocation();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private void setCurrentLocation()
{
myMapView = (MapView)findViewById(R.id.rescueMapView);
myMapView.setTraffic(true);
///myMapView.setBuiltInZoomControls(true);
myMapController = myMapView.getController();
myMapController.setZoom(16); //Fixed Zoom Level
myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
try
{
Criteria criteria = new Criteria();
provider = myLocationManager.getBestProvider(criteria, false);
Location location = myLocationManager.getLastKnownLocation(provider);
myLocationManager.requestLocationUpdates(
provider,
0,
0,
myLocationListener);
Location lastLocation = myLocationManager.getLastKnownLocation(provider);
if(lastLocation != null)
{
int lastLocLat =(int)(lastLocation.getLatitude()*1000000);
int lastLocLong =(int)(lastLocation.getLongitude()*1000000);
//Get the current location in start-up
GeoPoint initGeoPoint = new GeoPoint(lastLocLat,lastLocLong);
CenterLocatio(initGeoPoint);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Location Services Disabled")
.setMessage("The location service on the device are disabled, your location is not able to be found, please call AXA uding the button below to be rescued")
.setCancelable(false)
.setPositiveButton("Drop pin", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
CenterLocatio(defaultGeoPint);
}
});
builder.create().show();
}
}
catch (Exception e)
{
// TODO: handle exception
Context context = getApplicationContext();
String toasttext = e.getMessage();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, toasttext, duration);
toast.show();
}
}
private void CenterLocatio(GeoPoint centerGeoPoint)
{
myMapView.getOverlays().clear();
myMapController.animateTo(centerGeoPoint);
Drawable marker=getResources().getDrawable(R.drawable.marker);
marker.setBounds(0, 0, marker.getIntrinsicWidth(),
marker.getIntrinsicHeight());
int lat = centerGeoPoint.getLatitudeE6();
int lon = centerGeoPoint.getLongitudeE6();
double lat1 = centerGeoPoint.getLatitudeE6()/1E6;
double lon1 = centerGeoPoint.getLongitudeE6()/1E6;
ArrayList<Double> passing = new ArrayList<Double>();
passing.add(lat1);
passing.add(lon1);
Context context = getApplicationContext();
ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask();
task.applicationContext = context;
task.activityContext = rescue.this;
task.execute(passing);
myMapView.getOverlays().add(new SitesOverlay(marker,lat, lon ));
me=new MyLocationOverlay(this, myMapView);
myMapView.getOverlays().add(me);
};
private class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location argLocation) {
// TODO Auto-generated method stub
GeoPoint myGeoPoint = new GeoPoint(
(int)(argLocation.getLatitude()*1000000),
(int)(argLocation.getLongitude()*1000000));
//CenterLocatio(myGeoPoint);
}
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
}
}
private GeoPoint getPoint(int lat, int lon) {
return(new GeoPoint(lat, lon));
/*
return(new GeoPoint((int)(lat*1000000.0),
(int)(lon*1000000.0)));
*/
}
private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items=new ArrayList<OverlayItem>();
private Drawable marker=null;
private OverlayItem inDrag=null;
private ImageView dragImage=null;
private int xDragImageOffset=0;
private int yDragImageOffset=0;
private int xDragTouchOffset=0;
private int yDragTouchOffset=0;
public SitesOverlay(Drawable marker, int lat, int longitude) {
super(marker);
this.marker=marker;
dragImage=(ImageView)findViewById(R.id.drag);
xDragImageOffset=dragImage.getDrawable().getIntrinsicWidth()/2;
yDragImageOffset=dragImage.getDrawable().getIntrinsicHeight();
items.add(new OverlayItem(getPoint(lat,
longitude),
"UN", "United Nations"));
/*
items.add(new OverlayItem(getPoint(40.76866299974387,
-73.98268461227417),
"Lincoln Center",
"Home of Jazz at Lincoln Center"));
*/
populate();
}
#Override
protected OverlayItem createItem(int i) {
return(items.get(i));
}
#Override
public void draw(Canvas canvas, MapView mapView,
boolean shadow) {
super.draw(canvas, mapView, shadow);
boundCenterBottom(marker);
}
#Override
public int size() {
return(items.size());
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView) {
final int action=event.getAction();
final int x=(int)event.getX();
final int y=(int)event.getY();
boolean result=false;
if (action==MotionEvent.ACTION_DOWN) {
for (OverlayItem item : items) {
Point p=new Point(0,0);
myMapView.getProjection().toPixels(item.getPoint(), p);
if (hitTest(item, marker, x-p.x, y-p.y)) {
result=true;
inDrag=item;
items.remove(inDrag);
populate();
xDragTouchOffset=0;
yDragTouchOffset=0;
setDragImagePosition(p.x, p.y);
dragImage.setVisibility(View.VISIBLE);
xDragTouchOffset=x-p.x;
yDragTouchOffset=y-p.y;
break;
}
}
}
else if (action==MotionEvent.ACTION_MOVE && inDrag!=null) {
setDragImagePosition(x, y);
result=true;
}
else if (action==MotionEvent.ACTION_UP && inDrag!=null) {
dragImage.setVisibility(View.GONE);
GeoPoint pt=myMapView.getProjection().fromPixels(x-xDragTouchOffset,
y-yDragTouchOffset);
String title = inDrag.getTitle();
OverlayItem toDrop=new OverlayItem(pt, title,
inDrag.getSnippet());
items.add(toDrop);
populate();
double lat = pt.getLatitudeE6()/1E6;
double lon = pt.getLongitudeE6()/1E6;
ArrayList<Double> passing = new ArrayList<Double>();
passing.add(lat);
passing.add(lon);
Context context = getApplicationContext();
ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask();
task.applicationContext = context;
task.activityContext = rescue.this;
task.execute(passing);
//CenterLocatio(pt);
inDrag=null;
result=true;
}
return(result || super.onTouchEvent(event, mapView));
}
private void setDragImagePosition(int x, int y) {
RelativeLayout.LayoutParams lp=
(RelativeLayout.LayoutParams)dragImage.getLayoutParams();
lp.setMargins(x-xDragImageOffset-xDragTouchOffset,
y-yDragImageOffset-yDragTouchOffset, 0, 0);
dragImage.setLayoutParams(lp);
}
}
public class ReverseGeocodeLookupTask extends AsyncTask <ArrayList<Double>, Void, String>
{
private ProgressDialog dialog;
protected Context applicationContext;
protected Context activityContext;
#Override
protected void onPreExecute()
{
this.dialog = ProgressDialog.show(activityContext, "Please wait",
"Requesting location", true);
}
protected String doInBackground(ArrayList<Double>... params)
{
String foundAddress = "";
String localityName = "";
ArrayList<Double> passed = params[0];
double lat = passed.get(0);
double lon = passed.get(1);
try
{
List<Address> addresses = new Geocoder(applicationContext,Locale.getDefault()).getFromLocation(lat,lon, 1);
if (addresses.size() > 0)
{
String addressLine = "";
for(Integer i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
{
if(!addressLine.equals(""))
{
addressLine+= ", ";
}
addressLine+= addresses.get(0).getAddressLine(i);
}
if(addressLine!="")
{
foundAddress+= addressLine;
}
}
}
catch (Exception e) {
// TODO: handle exception
}
finally
{
}
return foundAddress;
}
#Override
protected void onPostExecute(String result)
{
this.dialog.cancel();
showToast(result);
}
}
public void showToast(String message)
{
Context context = getApplicationContext();
String toasttext = message;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, toasttext, duration);
toast.show();
}
}
Use below permission in manifest file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<uses-library android:name="com.google.android.maps" />
<activity
android:label="#string/app_name"
android:name=".DragAndDropPinActivity" >
</activity>
<activity
android:label="#string/app_name"
android:name=".rescue" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
The code shows below what i have done till now. Now what i need to do is, when i send an sms to the person i get his location back and that too i want to show the location on google map!!
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mehul.googlemaps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<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"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name">
<uses-library android:name="com.google.android.maps" />
<activity
android:name=".Main"
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=".HelloWorld" />
</application>
</manifest>
Main.java
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
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.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Main extends MapActivity implements LocationListener {
/** Called when the activity is first created. */
MapView map;
long start;
long stop;
int x, y;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
String towers;
int lat ;
int longi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Main.this, HelloWorld.class);
startActivity(intent);
}
});
map = (MapView)findViewById(R.id.mv);
map.setBuiltInZoomControls(true);
Touchy t = new Touchy();
overlayList = map.getOverlays();
overlayList.add(t);
d = getResources().getDrawable(R.drawable.pinn);
//Placing pintpoint
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Location location = lm.getLastKnownLocation(towers);
if (location != null){
lat = (int) (location.getLatitude() *1E6);
longi= (int) (location.getLongitude() *1E6);
GeoPoint ourLocation = new GeoPoint(lat,longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "Hi!!", "2nd");
CustomPinPoint custom = new CustomPinPoint(d, Main.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}else{
Toast.makeText(Main.this, "Couldnt get provider", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
lm.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
lm.requestLocationUpdates(towers, 500, 1, this );
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touchy extends Overlay{
public boolean onTouchEvent(MotionEvent e, MapView m){
if (e.getAction() == MotionEvent.ACTION_DOWN){
start = e.getEventTime();
}
if (e.getAction() == MotionEvent.ACTION_UP){
stop = e.getEventTime();
x = (int) e.getX();
y = (int) e.getY();
touchedPoint = map.getProjection().fromPixels(x, y);
}
if (stop - start > 1500){
AlertDialog alert = new AlertDialog.Builder(Main.this).create();
alert.setTitle("Pick Option");
alert.setButton("Hello", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
OverlayItem overlayItem = new OverlayItem(touchedPoint, "Hi!!", "2nd");
CustomPinPoint custom = new CustomPinPoint(d, Main.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}
});
alert.setButton3("Get Address", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() / 1E6, touchedPoint.getLongitudeE6() / 1E6 , 1);
if (address.size() > 0){
String display = "";
for (int i = 0; i<address.get(0).getMaxAddressLineIndex(); i++){
display += address.get(0).getAddressLine(i) + "\n";
}
Toast t = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
t.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
}
}});
alert.setButton2("Toggle View", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if (map.isSatellite()){
map.setSatellite(false);
map.setStreetView(true);
}else{
map.setStreetView(false);
map.setSatellite(true);
}
}
});
alert.setButton("Place a Pin", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
OverlayItem overlayItem = new OverlayItem(touchedPoint, "Hi!!", "2nd");
CustomPinPoint custom = new CustomPinPoint(d, Main.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}
});
alert.show();
return true;
}
return false;
}
}
public void onLocationChanged(Location l) {
// TODO Auto-generated method stub
lat = (int) (l.getLatitude() *1E6);
longi = (int) (l.getLongitude() *1E6);
GeoPoint ourLocation = new GeoPoint(lat,longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "Hi!!", "2nd");
CustomPinPoint custom = new CustomPinPoint(d, Main.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}
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
}
}
Helloworld.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class HelloWorld extends Activity
{
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.helloworld);
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "Content of the SMS goes here...");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
}
}
If anything else is required let me know.
Assuming the other person will also have your app installed, you could create a BroadcastReceiverwhich would respond to the android.provider.Telephony.SMS_RECEIVED action. The receiver should implement onReceive, detect if the message originated from your application (use some special key in the message body i guess?), extract the message and originating phone number from the extras in the received Intent, then trigger a location listener which would then send an SMS back...
The same BroadcastReceiver could also detect if the message has latitude/longitude in it, store the coordinates in some persistent storage, and send a broadcast intent to tell your MapActivity to update it's map with the new coordinates...
I am trying to get the address of a location. But the app does not show anything, only black screen.
I checked my Key, Android Manifest file. And everything on place.
package in.isuru.maps;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
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 android.app.AlertDialog;
import android.content.DialogInterface;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;
public class Main extends MapActivity {
MapView map;
long start;
long stop;
MyLocationOverlay compass;
MapController controller;
GeoPoint touchPoint;
int x, y;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
map = (MapView)findViewById(R.id.map_view_main);
map.setBuiltInZoomControls(true);
Touchy t = new Touchy();
List<Overlay> overlayList = map.getOverlays();
overlayList.add(t);
compass = new MyLocationOverlay(Main.this, map);
overlayList.add(compass);
//controller = map.getController();
//GeoPoint point = new GeoPoint(7865444, 79819940);
//controller.animateTo(point);
//controller.setZoom(6);
}
#Override
protected void onPause() {
compass.disableCompass();
super.onPause();
}
#Override
protected void onResume() {
compass.enableCompass();
super.onResume();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touchy extends Overlay{
public boolean onTouchEvent(MotionEvent e, MapView m){
if(e.getAction() == MotionEvent.ACTION_DOWN){
start = e.getEventTime();
x = (int) e.getX();
y = (int) e.getY();
touchPoint = map.getProjection().fromPixels(x, y);
}
if(e.getAction() == MotionEvent.ACTION_UP){
stop = e.getEventTime();
}
if(stop - start > 1500){
AlertDialog alert = new AlertDialog.Builder(Main.this).create();
alert.setTitle("Pick an Option");
alert.setMessage("Set the Place");
alert.setButton("Place a Pin", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
alert.setButton2("Get Address", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> address = geocoder.getFromLocation(touchPoint.getLatitudeE6()/1E6, touchPoint.getLongitudeE6() /1E6, 1);
if(address.size() > 0){
String display = "";
for(int i = 0; i < address.get(0).getMaxAddressLineIndex(); i++){
display += address.get(0).getAddressLine(i) + "\n";
}
Toast t = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
t.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
}
}
});
alert.setButton3("Place a Pin", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
alert.show();
return true;
}
return false;
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.isuru.maps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<uses-library android:name="com.google.android.maps" android:required="true"/>
<activity
android:name=".Main"
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>
</manifest>
I tried to add fake longitudes and latitude via Emulator control but it does not show anything either.
I think the error is not of Google Map its a problem because of the Geocoder class.
Please try your code with actual device and not in emulator and I am sure it will work.
As its found that Geocoder class doesn't work well in emulator.