I have put the google map service on by console, and generate a debug key.
I've debug it, the mMap and mLocation both are not null. I can get latitude and longitude successfully.
But the map is still blank.
Please help.
sam
here is the layout xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#f2f5fa"
tools:context=".LocFm" >
<!-- top bar component -->
<ImageView
android:id="#+id/loc_topbar"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:background="#drawable/topbar" />
<TextView
android:id="#+id/loc_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/loc_backBtn"
android:layout_centerHorizontal="true"
android:text="#string/loc_title"
android:textColor="#171717"
android:textSize="#dimen/title_font" />
<ImageView
android:id="#+id/loc_backBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/backbtn" />
<!-- BODY -->
<FrameLayout android:id="#+id/map_fragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/loc_topbar"
android:layout_above="#+id/loc_bottombar"
>
<!-- Put fragments dynamically -->
</FrameLayout>
<!-- bottom bar component -->
<ImageView
android:id="#+id/loc_bottombar"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#drawable/bottombar" />
<Button
android:id="#+id/locBtn"
android:layout_width="#dimen/halfbutton_width"
android:layout_height="#dimen/halfbutton_height"
android:layout_alignTop="#+id/loc_bottombar"
android:layout_alignParentLeft="true"
android:layout_marginTop="#dimen/halfbutton_marginTop"
android:background="#drawable/halfbutton_bg"
android:text="#string/button_Loc"
android:textSize="#dimen/button_font"/>
<Button
android:id="#+id/loc_nextBtn"
android:layout_width="#dimen/halfbutton_width"
android:layout_height="#dimen/halfbutton_height"
android:layout_alignTop="#+id/loc_bottombar"
android:layout_alignParentRight="true"
android:layout_marginTop="#dimen/halfbutton_marginTop"
android:background="#drawable/halfbutton_bg"
android:text="#string/button_Continue"
android:textSize="#dimen/button_font"/>
<ImageView
android:id="#+id/nextImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/loc_nextBtn"
android:layout_alignTop="#+id/loc_nextBtn"
android:layout_marginRight="#dimen/buttonicon_marginRight"
android:layout_marginTop="#dimen/buttonicon_marginTop"
android:src="#drawable/next" />
<ImageView
android:id="#+id/locImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/locBtn"
android:layout_alignTop="#+id/locBtn"
android:layout_marginRight="#dimen/buttonicon_marginRight"
android:layout_marginTop="#dimen/buttonicon_marginTop"
android:src="#drawable/location" />
</RelativeLayout>
Here is the manifest xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.map"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<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.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" >
</uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<permission
android:name="com.example.map.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.map.permission.MAPS_RECEIVE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/logo_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="my api key" />
<activity
android:name="com.example.map.LocFm"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name"
android:noHistory="true"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Java code:
package com.example.map;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
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.UiSettings;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class LocFm extends FragmentActivity implements OnClickListener, ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
Timer positionTimer;
private GoogleMap mMap;
private Location mLocation;
private UiSettings mUiSettings;
private LocationClient mLocationClient;
private static SupportMapFragment mMapView;
private static final String MAP_FRAGMENT_TAG = "map";
public FragmentManager fManager;
double latitude, longitude, radius;
String sLat,sLong,sRange;
boolean bMaploaded=false;
int index =0;
int positionCount=0;
final int POSITION_COUNT_MAX=5;
final int POSITION_MIN=100;
final int PSSITION_MAX_TIMES=10;
OnlineHistoryInfo onLineHistory;
ProgressDialog dialog;
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5000) // 5 seconds
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setLocFm();
}
#Override
public void onLocationChanged(Location location) {
if (mLocationClient != null && mLocationClient.isConnected())
{
mLocation=mLocationClient.getLastLocation();
}
if (mLocation!=null)
{
latitude= mLocation.getLatitude();
longitude= mLocation.getLongitude();
radius=mLocation.getAccuracy();
sLat=Double.toString(latitude);
sLong=Double.toString(longitude);
sRange=Double.toString(radius);
LatLng latLng = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mMap.addMarker(new MarkerOptions().position(latLng).title(getString(R.string.map_msg)));
}
positionCount++;
if(mLocationClient==null || radius<=POSITION_MIN)
{
mLocationClient.disconnect();
positionCount=0;
Button loc_nextBtn=(Button)findViewById(R.id.loc_nextBtn);
loc_nextBtn.setOnClickListener(this);
loc_nextBtn.setVisibility(View.VISIBLE);
ImageView nextImg=(ImageView)findViewById(R.id.nextImg);
nextImg.setVisibility(View.VISIBLE);
showDialog(false,null);
}
if(positionCount>=POSITION_COUNT_MAX)
{
mLocationClient.disconnect();
positionCount=0;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle connectionHint) {
setUpMapIfNeeded();
position();
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
private void mapDestroy()
{
if (mLocationClient != null)
mLocationClient.disconnect();
if(mMapView!=null){
FragmentTransaction ft = mMapView.getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(mMapView);
ft.commit();
}
if(mMap!=null)
{
mMap=null;
}
bMaploaded=false;
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the MapFragment.
mMap = mMapView.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
}
}
}
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(
this,
this, // ConnectionCallbacks
this); // OnConnectionFailedListener
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.loc_backBtn:
mapDestroy();
LocFm.this.finish();
break;
case R.id.loc_nextBtn:
positionCount=0;
mapDestroy();
break;
case R.id.locBtn:
relocate();
break;
}
}
public void setLocFm(){
setContentView(R.layout.loc_fm);
loadMapFragment();
ImageView loc_backBtn=(ImageView)findViewById(R.id.loc_backBtn);
loc_backBtn.setOnClickListener(this);
Button loc_nextBtn=(Button)findViewById(R.id.loc_nextBtn);
loc_nextBtn.setVisibility(View.GONE);
ImageView nextImg=(ImageView)findViewById(R.id.nextImg);
nextImg.setVisibility(View.GONE);
Button locBtn=(Button)findViewById(R.id.locBtn);
locBtn.setOnClickListener(this);
bMaploaded=true;
}
private void loadMapFragment() {
showDialog(true,getString(R.string.alert_postion));
// It isn't possible to set a fragment's id programmatically so we set a tag instead and
// search for it using that.
mMapView = (SupportMapFragment) getSupportFragmentManager()
.findFragmentByTag(MAP_FRAGMENT_TAG);
// We only create a fragment if it doesn't already exist.
if (mMapView == null) {
// To programmatically add the map, we first create a SupportMapFragment.
mMapView = SupportMapFragment.newInstance();
// Then we add it using a FragmentTransaction.
FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.map_fragment, mMapView, MAP_FRAGMENT_TAG);
fragmentTransaction.commit();
}
setUpLocationClientIfNeeded();
if (!mLocationClient.isConnected()) mLocationClient.connect();
}
private void position()
{
showDialog(true,getString(R.string.alert_postion));
if (mMap != null) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
mLocation = locationManager.getLastKnownLocation(provider);
mUiSettings = mMap.getUiSettings();
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(false);
// Check if we were successful in obtaining the map.
mLocationClient.requestLocationUpdates(REQUEST,this); // LocationListener
}
}
public void relocate()
{
if (!mLocationClient.isConnected()) mLocationClient.connect();
WSWLog.i("relocate()");
}
/**
* #param dialgShow
*/
public void showDialog(boolean dialgShow,final String message)
{
WSWLog.i(" showDialog ("+dialgShow+","+message+")");
if(dialgShow)
{
if(dialog==null)
{
dialog = new ProgressDialog(this);
dialog.setCancelable(false);//false
{
dialog.setMessage(message);
}
}
else
{
dialog.setMessage(message);
}
dialog.show();
//
if(null != positionTimer)
{
positionTimer.cancel();
}
positionTimer= new Timer(true);
TimerTask task = new TimerTask(){
public void run() {
handler.sendEmptyMessage(1);
}
};
positionTimer.schedule(task,PSSITION_MAX_TIMES*1000, PSSITION_MAX_TIMES*1000);
}
else
{
if(null != positionTimer)
{
positionTimer.cancel();
}
if(dialog!=null)
{
dialog.dismiss();
}
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if(null != positionTimer)
{
positionTimer.cancel();
}
showDialog(false,null);
//
alertNoPosition();
super.handleMessage(msg);
}
};
/**
*/
private void alertNoPosition()
{
AlertDialog.Builder builder = new Builder(this);
builder.setMessage(getString(R.string.loc_alert_realloc)); builder.setTitle(getString(R.string.button_Loc));
builder.setNegativeButton(getString(R.string.button_Cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
LocFm.this.finish();
}
});
builder.setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
relocate();
}
});
builder.create().show();
}
}
First check your debug key whether you are using right one? second use following permission. Remove repeated permission from manifest.xml.
<permission
android:name="com.example.map.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission
android:name="com.example.map.permission.MAPS_RECEIVE"
android:required="false" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"
android:required="false" />
Use supportmap fragment instead of simple fragment
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView)).getMap();
follow this simple tutorial you may find it usefull http://mobisys.in/blog/2012/12/google-rolls-out-android-maps-api-v2/
your code is not clear...
try this when you are showing lat-long on your map. i could not find this in your code
mCurrentLattitude = mGPSListener.GetLatitudeRaw();
mCurrentLongitude = mGPSListener.GetLongitudeRaw();
LatLng coordinates = new LatLng(mCurrentLattitude, mCurrentLongitude);
Log.d("MAP"," setCurrentLocation lat-lang values: "+mCurrentLattitude +" : "+mCurrentLongitude);
CameraUpdate center= CameraUpdateFactory.newLatLng(coordinates);
String lPreviousZoomLevelString = Config.getSetting(getApplicationContext(), "MAPZOOMLEVEL");
mPreviousZoomLevel = Float.parseFloat(lPreviousZoomLevelString);
CameraUpdate zoom=CameraUpdateFactory.zoomTo(mPreviousZoomLevel);
mMap.animateCamera(zoom);
CameraPosition i = mMap.getCameraPosition();
Log.d("MAP"," after setting zoom 2 :"+i.zoom);
mMap.moveCamera(center);
I still don't know what's happened. However, here is the step I took:
I took the advice by Gaurav Sharma, make the permission required="false"
This caused the onConnected() can't be triggered.
Then I changed the permission required="true". The map magically displayed! what a amazing google map!
Anyway, the map is shown. Don't know what's wrong. Thanks #GauravSharma
Related
I am having a problem using the Google Places Autocomplete SDK, I already found some answers, however, that didn't resolve the problen. In particular, related questions and answers were found here and here. The documentation on the Android developers site is here.
I activated the Places SDK for Android (and the Maps SDK for Android) and pasted the created API Key into my strings.xml file. The map is working just fine, however the autocomplete widget is closing immediately after selecting it and in the logcat I get the error:
05-23 06:00:40.376 14951-14951/com.example.tobi.beparty I/LOCATIONACTIVITY: An error occurred: Status{statusCode=ERROR, resolution=null}
Due to the linked answers, I was thinking that something is wrong with the API keys, however, in the Google APIs dashboard, I see every request (with an error rate of 100%), therefore I think this is not the problem. Moreover, I tried to implement the Place Autocomplete version with an intent (as described in the documentation) but faced the same problem which is why I think, the fragment is also not the problem.
Any suggestions? Many thanks in advance!
Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.tobi.beparty">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<application
android:name=".ParseApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key"/>
<activity android:name=".LogInActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<activity android:name=".MainActivity" />
<activity
android:name=".LocationActivity"
android:label="#string/title_activity_location">
</activity>
<activity android:name=".SearchActivity"/>
</application>
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tobi.beparty.LocationActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/relLayoutBotBar">
<fragment
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/map"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:elevation="10dp"
android:background="#drawable/white_border"
android:id="#+id/relLayout1">
<ImageView
android:layout_width="15dp"
android:layout_height="15dp"
android:id="#+id/ic_magnify"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:src="#drawable/ic_magnify"/>
<fragment
android:id="#+id/place_autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="#id/ic_magnify"
android:layout_marginLeft="5dp"
android:layout_centerVertical="true"
android:textSize="15sp"
android:textColor="#000"
android:background="#null"
android:hint="Enter the party name"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
/>
</RelativeLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/relLayoutBotBar"
android:layout_alignParentBottom="true">
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottomBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/white_grey_border_top"
app:menu="#menu/bottom_navigation_menu">
</android.support.design.widget.BottomNavigationView>
</RelativeLayout>
Java:
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.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;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class LocationActivity extends FragmentActivity implements OnMapReadyCallback {
final private String TAG = "LOCATIONACTIVITY";
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
EditText mSearchText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_layout);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// mSearchText = (EditText) findViewById(R.id.inputSearch);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
Log.i(TAG, "Place: " + place.getName());
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});
/* Bottom Navigationbar*/
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomBar);
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
Menu menu = bottomNavigationView.getMenu();
MenuItem menuItem = menu.getItem(3);
menuItem.setChecked(true);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.ic_search:
Intent intentSearch = new Intent(LocationActivity.this, MainActivity.class);
startActivity(intentSearch);
break;
case R.id.ic_favorite:
Intent intentFavorite = new Intent(LocationActivity.this, FavoriteActivity.class);
startActivity(intentFavorite);
break;
case R.id.ic_cake:
Intent intentParties = new Intent(LocationActivity.this, PartiesActivity.class);
startActivity(intentParties);
break;
case R.id.ic_location:
Intent intentLocation = new Intent(LocationActivity.this, LocationActivity.class);
startActivity(intentLocation);
break;
case R.id.ic_person:
Intent intentProfile = new Intent(LocationActivity.this, ProfileActivity.class);
startActivity(intentProfile);
break;
}
return false;
}
});
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
/* LatLng center = new LatLng(-34, 151);
String centerName = "Sydney"; */
LatLng center = new LatLng(13.307, 52.500068);
String centerName = "Adenauerplatz";
mMap.addMarker(new MarkerOptions().position(center).title("Marker in " + centerName));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(center, 10));
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, location.toString());
Toast.makeText(LocationActivity.this, location.toString(), Toast.LENGTH_SHORT).show();
// LatLng center = new LatLng(-34, 151);
LatLng center = new LatLng(location.getLatitude(), location.getLongitude());
String centerName = "current position";
mMap.clear();
mMap.addMarker(new MarkerOptions().position(center).title("Marker in " + centerName));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(center, 10));
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(listAddresses != null && listAddresses.size() > 0){
Log.i(TAG, listAddresses.get(0).toString());
String address = "";
if(listAddresses.get(0).getSubThoroughfare() != null){
address += listAddresses.get(0).getSubThoroughfare() + "";
}
if(listAddresses.get(0).getThoroughfare() != null){
address += listAddresses.get(0).getThoroughfare() + "";
}
if(listAddresses.get(0).getLocale() != null){
address += listAddresses.get(0).getLocale() + ", ";
}
if(listAddresses.get(0).getPostalCode() != null){
address += listAddresses.get(0).getPostalCode() + ", ";
}
if(listAddresses.get(0).getCountryName() != null){
address += listAddresses.get(0).getCountryName() + "";
}
Toast.makeText(LocationActivity.this, address, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (Build.VERSION.SDK_INT < 23) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
String lastKnownLocationName;
LatLng lastKnownLatLng;
if(lastKnownLocation == null){
lastKnownLatLng = new LatLng(52.500068, 13.307);
lastKnownLocationName = "Adenauerplatz";
}else{
lastKnownLatLng = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
lastKnownLocationName = "Last known location";
}
mMap.addMarker(new MarkerOptions().position(lastKnownLatLng).title(lastKnownLocationName));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(lastKnownLatLng, 10));
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); // ToDo: Die zahlen hier stehen dafür, wieviele Meter bzw. Sekunden gegangen werden müssen, dass ein Update erfolgt. evtl. ändern
}
}
}
}
I had this same issue when following the migration guide to use the Places compatibility library.
The problem is that Google considers the original "Places SDK for Android" and the new "Places API" two different APIs. As a result, you need to go into the Google Cloud Platform and enabled the new "Places API".
If you haven't enabled it yet, it will appear under the "Additional APIs" section - click on it, and then click on "Enable".
After you've enabled it, the new Places API should appear under the "Enabled APIs" section as shown below:
After I did this the autocomplete window stayed open and worked correctly.
I'm working on an app that will allow users to report potholes and other roadside issues easily. My specific issue is in the map I included; in the report activity that will allow users to pinpoint where the problem is by using google maps and some markers. To do this I'm basically copying code word for word from the google maps api and my problem is that the permission utils object isn't being inherited from google play services. I had put this code down for a while (out of frustration) so i dont exactly remember what the other issues were but i remember getting the code around permission utils to not give me an error was kind of a bitch. Anyway so please help ;_;. I apologize for how i space my code, it is just visually easier for me, the first block is the message activity, the second is my manifest. please let me know if I should post anything else.
package com.example.fixmytown;
import java.util.List;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.maps.SupportMapFragment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
public class Message extends FragmentActivity implements OnMyLocationButtonClickListener,
OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback {
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private boolean mPermissionDenied = false;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps_frag);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//----------------------------[Don't Mess with the above]------------------------------------------------------------
android.app.ActionBar actionBar = getActionBar();
//-------------------------------------------------------------------------------------------------------------------
//you were trying to figure out why the action bar isnt changing title. beinga bitch
String subject = " ";
if (Black.activityType == 1){
subject = "Pothole";
}
else if (Black.activityType == 2){
subject = "Roadkill";
}
else if (Black.activityType == 3){
subject = "Pollution";
}
else if(Black.activityType == 4){
// getActionBar().setTitle("Email Public Servant ");
}
}
//-------------------------------------------------------------------------------------------------------------------
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
mMap.setOnMyLocationButtonClickListener(this);
enableMyLocation();
}
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (mMap != null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
}
}
//-------------------------------------------------------------------------------------------------------------------
public void sendMessage(View view) {
EditText text = (EditText)findViewById(R.id.MessageText);
String Description = text.getText().toString();
String subject = "";
if (Black.activityType == 1){
subject = "Pothole";
}
else if (Black.activityType == 2){
subject = "Roadkill";
}
else if (Black.activityType == 3){
subject = "Pollution";
}
else if(Black.activityType == 4){
// getActionBar().setTitle("Email Public Servant ");
}
//-------------------------------------------------------------------------------------------------------------------
//email ability
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"mckippy#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, subject);
i.putExtra(Intent.EXTRA_TEXT , Description);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Message.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
//-------------------------------------------------------------------------------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.message, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onMyLocationButtonClick() {
// TODO Auto-generated method stub
return false;
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fixmytown"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="com.google.android.providers.gsf.permisson.READ_GSERVICES"/>
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
<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-sdk
android:minSdkVersion="11"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:screenOrientation="portrait"
android:name=".MainActivity"
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:screenOrientation="portrait"
android:name=".Black"
android:label="#string/title_activity_black" >
</activity>
<activity
android:screenOrientation="portrait"
android:name=".Green"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/title_activity_green"
android:theme="#style/FullscreenTheme" >
</activity>
<activity
android:screenOrientation="portrait"
android:name=".Message"
android:label="#string/title_activity_message" >
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyA0e26vc4-YGqmvOQSA6lQfnZyt3dmmbek"/>
</application>
</manifest>
I'm trying to find the location of the mobile using GPS and FusedLocationApi location. Even after enabling the GPS i'm not getting the location details. Below is the steps i followed. Kindly Help me Out.
Step 1:-
Added the line in my gradle
compile 'com.google.android.gms:play-services-location:8.1.0'
Step 2:-
MainActivity File
package com.developer.kamalasekar.locationfinder;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "MainActivity";
private TextView mLatitudeTextView;
private TextView mLongitudeTextView;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLatitudeTextView = (TextView) findViewById((R.id.latitude_textview));
mLongitudeTextView = (TextView) findViewById((R.id.longitude_textview));
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLocation != null) {
mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
} else {
Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
}
Step3:-
ActivityMain
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="#+id/latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Latitude:"
android:textSize="18sp" />
<TextView
android:id="#+id/latitude_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/latitude"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/latitude"
android:textSize="16sp" />
<TextView
android:id="#+id/longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Longitude:"
android:layout_marginTop="24dp"
android:textSize="18sp" />
<TextView
android:id="#+id/longitude_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/longitude"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/longitude"
android:textSize="16sp"/>
</RelativeLayout>
Step 4:-
Added the lines in my manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.developer.kamalasekar.locationfinder">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<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.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
There is a possibility that in onConnected if you call LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); may return null when location not found. But if you execute the same line again after few seconds (1/2 secs and gps enabled ) then you definitely get location for sure.
#Override
public void onConnected(Bundle bundle) {
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLocation != null) {
//your stuff
} else {
handler.sendEmptyMessageDelayed(1, 2000);
}
}
int count;
android.os.Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (count < 2) {
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLocation == null){
handler.sendEmptyMessageDelayed(1, 2000);
}else{
//your stuff
}
count++;
} else{
Log.i("MyTag","location not found");
}
}
};
or visit Android: Location Updates with the FusedLocationApi
or you can follow #user2450263 post by setting LocationListener.
So i put together a few snippets that i found here and there; aiming to make a more complex app, however, at one point i was able to obtain the the longitude and latitude number, but once I've tried supply those number to the reverse GeoCoding mechanism, i have not been able to get the Long and Lat numbers and the app crashes after i click the button (which does the reverse geocoding)
package com.example.com.example;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
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.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button myLocation;
TextView myAddress;
TextView textLat;
TextView textLong;
double latHolder = 0.0;
double longHolder = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLocation= (Button) findViewById(R.id.location);
myAddress = (TextView)findViewById(R.id.address);
textLat = (TextView)findViewById(R.id.textLat); ///COORDINATION VARIABLES1
textLong = (TextView)findViewById(R.id.textLong);///2
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); //gets it from the Operating system
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); //LOCATION UPDATED LINKED
if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
textLat.setText("GPS ONLINE (PLEASE WAIT)");
textLong.setText("GPS ONLINE (PLEASE WAIT)");
}
else
{
textLat.setText("GPS OFFLINE");
textLong.setText("GPS OFFLINE");
}
myLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getMyLocationAddress();
}
});
}
///////////COORDIATION ACQUIRING DOWN HERE
private class mylocationlistener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null)
{
double pLat = location.getLatitude();
double pLong = location.getLongitude();
textLat.setText(Double.toString(pLat));
textLong.setText(Double.toString(pLong));
latHolder = pLat;
longHolder = pLong;
}
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
public void getMyLocationAddress() {
Geocoder geocoder= new Geocoder(this, Locale.ENGLISH);
try {
//Place your latitude and longitude
List<Address> addresses = geocoder.getFromLocation(latHolder,longHolder, 1);
if(addresses != null) {
Address fetchedAddress = addresses.get(0);
StringBuilder strAddress = new StringBuilder();
for(int i=0; i<fetchedAddress.getMaxAddressLineIndex(); i++) {
strAddress.append(fetchedAddress.getAddressLine(i)).append("\n");
}
myAddress.setText("I am at: " +strAddress.toString());
}
else
myAddress.setText("No location found..!");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Could not get address..!", Toast.LENGTH_LONG).show();
}
}
}
Here is my Manafist with all permissions which should be enough
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<permission android:name="com.example.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
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>
and last but not lease my xml layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LATITUDE" />
<Button
android:id="#+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/address"
android:layout_below="#+id/address"
android:layout_marginTop="79dp"
android:text="get_location" />
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title"
android:layout_marginTop="135dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title"
android:layout_marginTop="44dp"
android:text="LONGITUD" />
<TextView
android:id="#+id/textLong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="26dp" />
<TextView
android:id="#+id/textLat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title" />
</RelativeLayout>
DO PLEASE NOTE! i have added two global variables called LongHolder and LatHolder to pass the values of the GPS straight to the reverse geocoding. I believe they failed their purpose but if you need to test random selected Coordinates yourself, remember to remove them. THANK YOU
I have it set up so OnClick should launch a new activity but when I press the button (button1) nothing happens. I want it to open my Google Maps function but it won't work. It doesn't crash or anything, just nothing happens when I press button1 which should launch MainActivity & activity_main.xml. LogCat won't give me anything useful to go on either.
MainMenu.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".NewActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Club Deals"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="GPS locations"
android:onClick="OnClickListener"/>
<Button
android:id="#+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Closest Deals"
android:onClick="open_close_deals" />
<Button
android:id="#+id/button6"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Cheapest Deals"
android:onClick="open_cheap_deals" />
<Button
android:id="#+id/button7"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Best Value Deals"
android:onClick="best_value" />
<Button
android:id="#+id/button8"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Best Events"
android:onClick="best_events" />
<Button
android:id="#+id/button9"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="News"
android:onClick="news"/>
</LinearLayout>
This is my launch activity for the menu:
package com.kieranmaps.v2maps;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
public class NewActivity extends FragmentActivity {
public void addListenerOnButtonNews() {
Button button = (Button) findViewById(R.id.button9);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), NewActivity.class);
startActivity(intent);
}
});
}
;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
}
public void addListenerButtonGPS() {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
setContentView(R.layout.activity_main);
}});
}
}
This is the activity, that's supposed to launch a GPS map
MainActivity:
package com.kieranmaps.v2maps;
import java.util.Hashtable;
import android.content.Context;
import android.location.Location;
import android.app.ActivityManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.kieranmaps.v2maps.R;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.FIFOLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
public class MainActivity extends FragmentActivity {
private GoogleMap googleMap;
private final LatLng OREILLYS = new LatLng(53.348347, -6.254119);
private final LatLng LAGOONA = new LatLng(53.349810, -6.243160);
private final LatLng COPPERS = new LatLng (53.335356, -6.263481);
private final LatLng WRIGHTS = new LatLng (53.445491, -6.223857);
private final LatLng ACADEMY = new LatLng (53.348045,-6.26198);
private final LatLng DICEYS = new LatLng (53.347250, -6.254198);
private final LatLng PYGMALION = new LatLng (53.342183,-6.262358);
private final LatLng FIBBERS = new LatLng (53.352799,-6.260412);
// private final LatLng TEST = new LatLng (5352799,-6.260412);
private Marker marker;
private Hashtable<String, String> markers;
private ImageLoader imageLoader;
private DisplayImageOptions options;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
initImageLoader();
markers = new Hashtable<String, String>();
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_launcher) // Display Stub Image
.showImageForEmptyUri(R.drawable.ic_launcher) // If Empty image found
.cacheInMemory()
.cacheOnDisc().bitmapConfig(Bitmap.Config.RGB_565).build();
if ( googleMap != null ) {
googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
final Marker oreillys = googleMap.addMarker(new MarkerOptions().position(OREILLYS)
.title("O Reillys"));
markers.put(oreillys.getId(), "http://img.india-forums.com/images/100x100/37525-a-still-image-of-akshay-kumar.jpg");
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(OREILLYS, 15));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
final Marker coppers = googleMap.addMarker(new MarkerOptions().position(COPPERS)
.title("Coppers"));
markers.put(coppers.getId(), "http://f3.thejournal.ie/media/2011/11/coppers1-390x285.png");
final Marker wrights = googleMap.addMarker(new MarkerOptions().position(WRIGHTS)
.title("The Wright Venue"));
markers.put(wrights.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker lagoona = googleMap.addMarker(new MarkerOptions().position(LAGOONA)
.title("The Lagoona"));
markers.put(lagoona.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker academy = googleMap.addMarker(new MarkerOptions().position(ACADEMY)
.title("The Academy"));
markers.put(academy.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker pygmalion = googleMap.addMarker(new MarkerOptions().position(PYGMALION)
.title("The Pygmalion"));
markers.put(pygmalion.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker fibbers = googleMap.addMarker(new MarkerOptions().position(FIBBERS)
.title("Fibbers"));
markers.put(fibbers.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker diceys = googleMap.addMarker(new MarkerOptions().position(DICEYS)
.title("Dicey's"));
markers.put(diceys.getId(), "https://dublinnow.files.wordpress.com/2012/05/diceys.jpg");
/* final Marker diceys = googleMap.addMarker(new MarkerOptions()
.position(DICEYS)
.title("Diceys")
.snippet("Drink Deal: 3.50. Adm: 5, Performance: Gen"));
Marker marker = GoogleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Title")
.snippet("Snippet")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker))); */
//marker.showInfoWindow();
}
}
private class CustomInfoWindowAdapter implements InfoWindowAdapter {
private View view;
public CustomInfoWindowAdapter() {
view = getLayoutInflater().inflate(R.layout.custom_info_window,
null);
}
#Override
public View getInfoContents(Marker marker) {
if (MainActivity.this.marker != null
&& MainActivity.this.marker.isInfoWindowShown()) {
MainActivity.this.marker.hideInfoWindow();
MainActivity.this.marker.showInfoWindow();
}
return null;
}
#Override
public View getInfoWindow(final Marker marker) {
MainActivity.this.marker = marker;
String url = null;
if (marker.getId() != null && markers != null && markers.size() > 0) {
if ( markers.get(marker.getId()) != null &&
markers.get(marker.getId()) != null) {
url = markers.get(marker.getId());
}
}
final ImageView image = ((ImageView) view.findViewById(R.id.badge));
if (url != null && !url.equalsIgnoreCase("null")
&& !url.equalsIgnoreCase("")) {
imageLoader.displayImage(url, image, options,
new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view,
loadedImage);
getInfoContents(marker);
}
});
} else {
image.setImageResource(R.drawable.ic_launcher);
}
//
final String title = marker.getTitle();
final TextView titleUi = ((TextView) view.findViewById(R.id.title));
if (title != null) {
titleUi.setText(title);
} else {
titleUi.setText("");
}
final String snippet = marker.getSnippet();
final TextView snippetUi = ((TextView) view
.findViewById(R.id.snippet));
if (snippet != null) {
snippetUi.setText(snippet);
} else {
snippetUi.setText("");
}
return view;
}
}
private void initImageLoader() {
int memoryCacheSize;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
int memClass = ((ActivityManager)
getSystemService(Context.ACTIVITY_SERVICE))
.getMemoryClass();
memoryCacheSize = (memClass / 8) * 1024 * 1024;
} else {
memoryCacheSize = 2 * 1024 * 1024;
}
googleMap.setMyLocationEnabled(true);
final ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
this).threadPoolSize(5)
.threadPriority(Thread.NORM_PRIORITY - 2)
.memoryCacheSize(memoryCacheSize)
.memoryCache(new FIFOLimitedMemoryCache(memoryCacheSize-1000000))
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO).enableLogging()
.build();
ImageLoader.getInstance().init(config);
}
public void onLocationChanged(Location loc){
googleMap.setMyLocationEnabled(true);
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kieranmaps.v2maps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission
android:name="com.ngshah.googlemapv2.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.ngshah.googlemapv2.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-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<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" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyACv08wBcZ2io9lTwm2OYY1XnSx4CvT8nE" />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="com.kieranmaps.v2maps.MainActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.kieranmaps.v2maps.NewActivity"
android:label="#string/new_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Mapview (called activity_main.xml)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
Try changing the name of either button so you don't have the same variable names in different methods.
As far as i can see you don't call public void addListenerOnButtonNews() and public void addListenerButtonGPS() anyware.You just declare them. Try putting the code from those two methods in onCreate() and use different name for each button like the example below :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}});
Button button9 = (Button) findViewById(R.id.button9);
button9.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), NewActivity.class);
startActivity(intent);
}
});
}
I have also deleted the setContentView(R.layout.activity_main); from button1 onclick method because its not needed.
I think the main problem lies here:
Button button = (Button) findViewById(R.id.button9);
Button button = (Button) findViewById(R.id.button1);
you have created references of Button with the same name.Try changing any one of them like:
Button button1 = (Button) findViewById(R.id.button1);