Place Autocomplete closes immediately - android

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.

Related

Create a menu to switch between different types of map (Google Map API on Android)

I am developing a map app with Google Map V2 on Android Studio 2.3 and I would like to create a menu that allows to switch between different types of map. Below is my MapActivity.java code. Please help.
package net.dada.thm;
import android.database.sqlite.SQLiteOutOfMemoryException;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
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 com.google.firebase.appindexing.Action;
import com.google.firebase.appindexing.FirebaseUserActions;
import com.google.firebase.appindexing.builders.Actions;
import static net.dada.thm.R.id.map;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
public GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in LOME
LatLng LOME = new LatLng(6.131944, 1.222778);
mMap.addMarker(new MarkerOptions().position(LOME).title("LOME"));
}
You could try this approach:
Create one activity with:
MAPTYPE_ONE tab
MAPTYPE_TWO tab
Example
mMap.setBuildingsEnabled(true);
final float mCameraZoom = 10.00f;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); //this part;
mMap.setTrafficEnabled(true);
mMap.setIndoorEnabled(true);
so then when you select the first tab, you can see the first type of the map and the second one, you set the map type accordingly;
You really don't need a menu; just a small ViewPager with two items on it!
I hope it helps!
I was able to create Buttons inside LinearLayout with onClick attributes to change map types. However, I lost my app initial state in the layout. I don't know where to insert the following paramters:
map:cameraTargetLat="8.6253268"
map:cameraTargetLng="-1.4193078"
map:cameraTilt="00"
map:cameraZoom="6.5"
map:cameraBearing="00"
map:mapType="normal"
map:uiCompass="true"
map:uiRotateGestures="false"
map:uiScrollGestures="true"
map:uiTiltGestures="false"
map:uiZoomControls="true"
map:uiZoomGestures="true"
Or do I have some scripts in the MapsActiviti.java file that is incompatible to what I want to add to the Activity_maps.xml file? Please help.
Activity_maps.xml file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="horizontal">
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:hint="Search Location" />
<Button
android:id="#+id/search_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:onClick="onMapSearch"
android:text="Search" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Type: " />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onNormalMap"
android:text="Normal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onSatelliteMap"
android:text="Satellite" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onTerrainMap"
android:text="Terrain" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onHybridMap"
android:text="Hybrid" />
</LinearLayout>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="net.dada.thm.MapsActivity"/>
</LinearLayout>
MapsActivity.java file:
package net.dada.thm;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.EditText;
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;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
}
public void onMapSearch(View view) {
EditText locationSearch = (EditText) findViewById(R.id.editText);
String location = locationSearch.getText().toString();
List<Address> addressList = null;
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
assert addressList != null;
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
public void onNormalMap(View view) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
public void onSatelliteMap(View view) {
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
public void onTerrainMap(View view) {
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
}
public void onHybridMap(View view) {
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in TSEVIE
LatLng TSEVIE = new LatLng(6.433333, 1.21666);
mMap.addMarker(new MarkerOptions().position(TSEVIE).title("TSEVIE"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(TSEVIE ));
// Add a marker in ATAKPAME
LatLng ATAKPAME = new LatLng(7.526944, 1.126669);
mMap.addMarker(new MarkerOptions().position(ATAKPAME).title("ATAKPAME"));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
}

LocationManager doesn't work, without any error

If I click "Find My Location" button, then my location information should have shown on the TextView, but doesn't work.
It's simple code but I have no idea where did this go wrong. Seems that there's no mistake within the code.. could be the problem of my phone?
MainActivity.java
package org.androidtown.mylocation;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
}
public void onButton1Clicked(View v){
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
long minTime = 10000;
float minDistance = 0;
MyLocationListener listener = new MyLocationListener();
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
minTime, minDistance, listener);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
minTime, minDistance, listener);
Location lastLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastLocation != null){
Double latitude = lastLocation.getLatitude();
Double longitude = lastLocation.getLongitude();
textView.setText("My Latest Location: " + latitude + ", " + longitude);
textView.invalidate();
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
textView.setText("My Location: " + latitude + ", " + longitude);
textView.invalidate();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.androidtown.mylocation" >
<!-- GPS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!-- NETWORK -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/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>
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" 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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Find My Location"
android:id="#+id/button"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:onClick="onButton1Clicked" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Location"
android:id="#+id/textView"
android:layout_below="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="83dp" />
</RelativeLayout>

Show Listview on googlemaps activity

I'm trying to show list view on the bottom side of the google maps activity (only when the button is clicked), but it doesn't work, just showing app stop message. How can I show listview on google maps activity?
Here is my java and xml code
package com.example.dong_gyo.project;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
public class MapFind extends ActionBarActivity {
GoogleMap mMap; // Might be null if Google Play services APK is not available.
LocationManager lm;
String locationProvider;
Location location;
Button mapListbut;
ListView mapList;
ArrayList list;
ButtonListener listener;
ArrayAdapter mapadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_find);
setUpMapIfNeeded();
mapListbut = (Button)findViewById(R.id.showMapList);
mapadapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
mapList = (ListView)findViewById(R.id.mapList);
mapList.setAdapter(mapadapter);
mapList.setVisibility(View.INVISIBLE);
mapListbut.setOnClickListener(listener);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationProvider = lm.getBestProvider(new Criteria(), true);
location = lm.getLastKnownLocation(locationProvider);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
final LatLng LOC = new LatLng(latitude, longitude);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(LOC, 16));
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap(LOC);
}
}
}
private void setUpMap(LatLng LOC) {
mMap.addMarker(new MarkerOptions().position(LOC));
}
class ButtonListener implements View.OnClickListener {
#Override
public void onClick(View v) { // 목록 토글 버튼 리스너
// TODO Auto-generated method stub
switch (v.getId()) { //
case R.id.showMapList:
if (!mapList.isShown()) {
mapList.setVisibility(View.VISIBLE);
mapadapter.notifyDataSetChanged();
mapListbut.setSelected(true);
} else {
mapList.setVisibility(View.INVISIBLE);
mapListbut.setSelected(false);
}
break;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
startActivity(new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
XML :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<fragment 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:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
<Button
android:id="#+id/showMapList"
android:text = "목록보기"
android:layout_width="100dp"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"/>
<ListView
android:id="#+id/mapList"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#eeeeee" >
</ListView>
</RelativeLayout>
I ran your code and it said it gets a null pointer. Looking at your code, location = lm.getLastKnownLocation(locationProvider); makes location to be null. So, instead of the getBestProvider, try:
location = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
I tried it and the maps load.

Android Button to launch new activity does not do anything when clicked

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);

google map blank screen, programmatic added

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

Categories

Resources