How to transfer data from one activity to another? Android application [duplicate] - android

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 8 years ago.
I want to trasfer data (a longitude and a latitude) from one activity to another. The goal is to transfer this data to the camera, to see how the objects (augmented reality) move in real-time.
LocationGoogleMap.class
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.beyondar.android.plugin.googlemap.GoogleMapWorldPlugin;
import com.beyondar.android.world.GeoObject;
import com.beyondar.android.world.World;
import com.example.pfg_v7.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
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;
public class LocationGoogleMap extends FragmentActivity implements
OnMarkerClickListener, OnClickListener, LocationListener {
private GoogleMap mMap;
private GoogleMapWorldPlugin mGoogleMapPlugin;
private World mWorld;
Marker mMark;
private LocationManager oLoc;
private Location currentLoc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_google);
Button myLocationButton = (Button) findViewById(R.id.myLocationButton);
myLocationButton.setVisibility(View.VISIBLE);
myLocationButton.setOnClickListener(this);
Criteria oGPSSettings = new Criteria();
oGPSSettings.setAccuracy(Criteria.ACCURACY_FINE);
oGPSSettings.setSpeedRequired(true);
oGPSSettings.setAltitudeRequired(true);
oGPSSettings.setBearingRequired(true);
oGPSSettings.setCostAllowed(false);
oGPSSettings.setPowerRequirement(Criteria.POWER_MEDIUM);
oLoc = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = oLoc.getBestProvider(oGPSSettings, true);
if (provider != null) {
oLoc.requestLocationUpdates(provider, 1000, 1, this);
} else {
Toast.makeText(getBaseContext(), "No GPS", Toast.LENGTH_SHORT)
.show();
finish();
}
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
if (mMap == null) {
return;
}
// We create the world and fill the world
mWorld = CreateWorld.generateObjects(this);
// As we want to use GoogleMaps, we are going to create the plugin and
// attach it to the World
mGoogleMapPlugin = new GoogleMapWorldPlugin(this);
// Then we need to set the map into the GoogleMapPlugin
mGoogleMapPlugin.setGoogleMap(mMap);
// Now that we have the plugin created let's add it to our world.
// NOTE: It is better to load the plugins before start adding object in
// to the world.
mWorld.addPlugin(mGoogleMapPlugin);
mMap.setOnMarkerClickListener(this);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mGoogleMapPlugin.getLatLng(), 15));
mMap.animateCamera(CameraUpdateFactory.zoomTo(19), 2000, null);
}
#Override
public void onLocationChanged(Location location) {
currentLoc = location;
LatLng oPos = new LatLng(currentLoc.getLatitude(),
currentLoc.getLongitude());
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
if (mMap != null) {
mMap.clear();
mMark = mMap.addMarker(new MarkerOptions().position(oPos).title(
"My Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(oPos, 17));
}
// We create the world and fill the world
mWorld = CreateWorld.generateObjects(this);
// As we want to use GoogleMaps, we are going to create the plugin and
// attach it to the World
mGoogleMapPlugin = new GoogleMapWorldPlugin(this);
// Then we need to set the map into the GoogleMapPlugin
mGoogleMapPlugin.setGoogleMap(mMap);
// Now that we have the plugin created let's add it to our world.
// NOTE: It is better to load the plugins before start adding object in
// to the world.
mWorld.addPlugin(mGoogleMapPlugin);
}
/*
*
* mMap = ((SupportMapFragment)
* getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); if
* (mMap == null) { return; }
*
* // We create the world and fill the world mWorld =
* CreateWorld.generateObjects(this);
*
*
*
* // As we want to use GoogleMaps, we are going to create the plugin and //
* attach it to the World mGoogleMapPlugin = new GoogleMapWorldPlugin(this);
* // Then we need to set the map into the GoogleMapPlugin
* mGoogleMapPlugin.setGoogleMap(mMap); // Now that we have the plugin
* created let's add it to our world. // NOTE: It is better to load the
* plugins before start adding object in // to the world.
* mWorld.addPlugin(mGoogleMapPlugin);
*
* //NO
* AÑADIDO//////----------------------------------------////////////////
* ////////////////////////////////////////
* mMap.setOnMarkerClickListener(this);
*
* mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mGoogleMapPlugin.getLatLng
* (), 15)); mMap.animateCamera(CameraUpdateFactory.zoomTo(19), 2000, null);
* //NO
* AÑADIDO/////-----------------------------------------////////////////
* /////////////////////////////////////////
*
* // Lets add the user position to the map GeoObject user = new
* GeoObject(1000l); user.setGeoPosition(mWorld.getLatitude(),
* mWorld.getLongitude()); user.setImageResource(R.drawable.flag);
* user.setName("User position"); mWorld.addBeyondarObject(user);
*
* BeyondarLocationManager.addWorldLocationUpdate(mWorld);
* BeyondarLocationManager.addGeoObjectLocationUpdate(user);
*
* // We need to set the LocationManager to the BeyondarLocationManager.
* BeyondarLocationManager .setLocationManager((LocationManager)
* getSystemService(Context.LOCATION_SERVICE));
*/
#Override
public boolean onMarkerClick(Marker marker) {
// To get the GeoObject that owns the marker we use the following
// method:
GeoObject geoObject = mGoogleMapPlugin.getGeoObjectOwner(marker);
if (geoObject != null) {
Toast.makeText(
this,
"Click on a marker owned by a GeoOject with the name: "
+ geoObject.getName(), Toast.LENGTH_SHORT).show();
}
return false;
}
#Override
protected void onResume() {
super.onResume();
// When the activity is resumed it is time to enable the
// BeyondarLocationManager
oLoc.removeUpdates(this);
oLoc.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
}
#Override
protected void onPause() {
super.onPause();
// To avoid unnecessary battery usage disable BeyondarLocationManager
// when the activity goes on pause.
oLoc.removeUpdates(this);
}
#Override
public void onClick(View v) {
// When the user clicks on the button we animate the map to the user
// location
LatLng userLocation = new LatLng(currentLoc.getLatitude(),
currentLoc.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
mMap.animateCamera(CameraUpdateFactory.zoomTo(19), 2000, null);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
oLoc.removeUpdates(this);
oLoc.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
}
#Override
public void onProviderEnabled(String provider) {
oLoc.removeUpdates(this);
oLoc.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
Toast.makeText(getBaseContext(), provider + " is enabled.",
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
oLoc.removeUpdates(this);
Toast.makeText(getBaseContext(), provider + " is disabled.",
Toast.LENGTH_SHORT).show();
}
}
CameraWithLocation.class
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import com.beyondar.android.fragment.BeyondarFragmentSupport;
import com.beyondar.android.world.World;
public class CameraWithLocation extends FragmentActivity implements
OnSeekBarChangeListener, OnClickListener {
private BeyondarFragmentSupport mBeyondarFragment;
private World mWorld;
private SeekBar mSeekBarMax, mSeekBarMin;
private Button mShowMap;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
loadViewFromXML();
// We create the world and fill it ...
mWorld = CreateWorld.generateObjects(this);
// .. and send it to the fragment
mBeyondarFragment.setWorld(mWorld);
// We also can see the Frames per seconds
mBeyondarFragment.showFPS(true);
}
private void loadViewFromXML() {
setContentView(R.layout.camera_with_location);
mBeyondarFragment = (BeyondarFragmentSupport) getSupportFragmentManager()
.findFragmentById(R.id.beyondarFragment);
mSeekBarMax = (SeekBar) findViewById(R.id.seekBarMax);
mSeekBarMin = (SeekBar) findViewById(R.id.seekBarMin);
mSeekBarMax.setOnSeekBarChangeListener(this);
mSeekBarMin.setOnSeekBarChangeListener(this);
mSeekBarMax.setMax(100);
mSeekBarMin.setMax(100);
mShowMap = (Button) findViewById(R.id.showMapButton);
mShowMap.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == mShowMap) {
Intent intent = new Intent(this, LocationGoogleMap.class);
startActivity(intent);
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (seekBar == mSeekBarMax) {
mBeyondarFragment.setMaxFarDistance(progress);
} else if (seekBar == mSeekBarMin) {
mBeyondarFragment.setMinFarDistanceSize(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
CreateWorld.class
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.widget.Toast;
import com.beyondar.android.plugin.googlemap.GoogleMapWorldPlugin;
import com.beyondar.android.world.GeoObject;
import com.beyondar.android.world.World;
import com.example.pfg_v7.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class CreateWorld{
public static final int LIST_TYPE_EXAMPLE_1 = 1;
public static World sharedWorld;
public static World generateObjects(Context context) {
if (sharedWorld != null) {
return sharedWorld;
}
sharedWorld = new World(context);
// The user can set the default bitmap. This is useful if you are
// loading images form Internet and the connection get lost
sharedWorld.setDefaultImage(R.drawable.beyondar_default_unknow_icon);
// User position (you can change it using the GPS listeners form Android
// API)
sharedWorld.setGeoPosition(40.332177, -3.766126);
// Create an object with an image in the app resources.
GeoObject go1 = new GeoObject(1l);
go1.setGeoPosition(40.390691, -3.636787);
go1.setImageResource(R.drawable.rectangle);
go1.setName("CercaDeCasa");
GeoObject go2 = new GeoObject(2l);
go2.setGeoPosition(40.391076, -3.635275);
go2.setImageResource(R.drawable.rectangle);
go2.setName("Cruce Superior");
GeoObject go3 = new GeoObject(3l);
go3.setGeoPosition(40.390821, -3.635967);
go3.setImageResource(R.drawable.rectangle);
go3.setName("Cruce del parque");
GeoObject go4 = new GeoObject(4l);
go4.setGeoPosition(40.390288, -3.635356);
go4.setImageResource(R.drawable.rectangle);
go4.setName("Callejuela");
// Add the GeoObjects to the world
sharedWorld.addBeyondarObject(go1);
sharedWorld.addBeyondarObject(go2);
sharedWorld.addBeyondarObject(go3);
sharedWorld.addBeyondarObject(go4);
return sharedWorld;
}
}
To sum up: I'd need to give to the Camera class the information about my location.

For example :
In MainActivity :
Intent intent = new Intent();
intent.setClass(this, Other_Activity.class);
intent.putExtra("EXTRA_ID", "SOME DATAS");
startActivity(intent);
In Other_Activity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String datas= extras.getString("EXTRA_ID");
if (datas!= null) {
// do stuff
}
}
More informations here :
http://developer.android.com/reference/android/content/Intent.html
taken from here: Simple example for Intent and Bundle

Check this link please..
It says..
Use this to "put" the file...
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String keyIdentifer = null;
i.putExtra("STRING_I_NEED", strName);
startActivity(i);
Then, to retrieve the value try something like:
String newString;
if (savedInstanceState == null) {
extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}

Related

How to include GeoJson using open street map in android?

I'm using Open Street Map, and I need to save my added points inside a GeoJson so that I can then visualize these points according to the saved coordinates, time, and open within an analyzer of that type of file.
At the first moment, I do not have much data. I only have code using Open Street Map, which still needs some changes.
package br.com.josileudorodrigues.myapplication;
import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.cocoahero.android.geojson.GeoJSON;
import org.osmdroid.bonuspack.kml.KmlDocument;
import org.osmdroid.bonuspack.location.NominatimPOIProvider;
import org.osmdroid.bonuspack.location.POI;
import org.osmdroid.config.Configuration;
import org.osmdroid.events.MapEventsReceiver;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.Projection;
import org.osmdroid.views.overlay.FolderOverlay;
import org.osmdroid.views.overlay.MapEventsOverlay;
import org.osmdroid.views.overlay.Marker;
import org.osmdroid.views.overlay.MinimapOverlay;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;
import org.osmdroid.views.overlay.PathOverlay;
import org.osmdroid.views.overlay.ScaleBarOverlay;
import org.osmdroid.views.overlay.compass.CompassOverlay;
import org.osmdroid.views.overlay.compass.InternalCompassOrientationProvider;
import org.osmdroid.views.overlay.infowindow.InfoWindow;
import org.osmdroid.views.overlay.infowindow.MarkerInfoWindow;
import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider;
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.ArrayList;
import static android.os.Build.VERSION_CODES.M;
import static java.security.AccessController.getContext;
public class MainActivity extends AppCompatActivity implements MapEventsReceiver, LocationListener {
private static final int PERMISSAO_REQUERIDA =1 ;
private MapView osm;
private MapController mc;
private CompassOverlay mCompassOverlay;
private MyLocationNewOverlay mLocationOverlay;
private LocationManager locationManager;
private PathOverlay po;
private KmlDocument kmlDocument;
ArrayList<OverlayItem> overlayItemArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//onde mostra a imagem do mapa
Context ctx = getApplicationContext();
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
setContentView(R.layout.activity_main);
//Essa é para poder utilizar as permissões
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
osm = (MapView) findViewById(R.id.mapaId);
osm.setTileSource(TileSourceFactory.MAPNIK);
osm.setUseDataConnection(true);
osm.setMultiTouchControls(true);
osm.setClickable(true);
osm.setBuiltInZoomControls(true);
if (Build.VERSION.SDK_INT >= M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] permissoes = {Manifest.permission.INTERNET, Manifest.permission.ACCESS_FINE_LOCATION};
requestPermissions(permissoes, PERMISSAO_REQUERIDA);
}
}
if (Build.VERSION.SDK_INT >= M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
String[] permissoes = {Manifest.permission.INTERNET, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissoes, PERMISSAO_REQUERIDA);
}
}
osm.setMapListener(new MapListener() {
#Override
public boolean onScroll(ScrollEvent event) {
Log.i("Script()", "onScroll ()");
return true;
}
#Override
public boolean onZoom(ZoomEvent event) {
Log.i("Script()", "onZoom ()");
return false;
}
});
mc = (MapController) osm.getController();
GeoPoint center = new GeoPoint(-5.1251, -38.3640);
mc.setZoom(14);
mc.animateTo(center);
addMarker(center);
/* locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//TODO: Consider calling
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);*/
MapEventsOverlay mapEventsOverlay = new MapEventsOverlay(this, this);
osm.getOverlays().add(0, mapEventsOverlay);
// Aqui adiciona a escala do mapa
ScaleBarOverlay scaleBarOverlay = new ScaleBarOverlay(osm);
osm.getOverlays().add(scaleBarOverlay);
kmlDocument = new KmlDocument();
// kmlDocument.parseGeoJSON(geoJsonString);
/*this.mLocationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(ctx),osm);
this.mLocationOverlay.enableMyLocation();
osm.getOverlays().add(this.mLocationOverlay);*/
this.mCompassOverlay = new CompassOverlay(this, new InternalCompassOrientationProvider(this), osm);
this.mCompassOverlay.enableCompass();
osm.getOverlays().add(this.mCompassOverlay);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSAO_REQUERIDA: {
// Se a solicitação de permissão foi cancelada o array vem vazio.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permissão cedida, recria a activity para carregar o mapa, só será executado uma vez
this.recreate();
}
}
}
}
public void addMarker(final GeoPoint center) {
final Marker marker = new Marker(osm);
marker.setPosition(center);
marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
marker.setIcon(getResources().getDrawable(R.drawable.ic_mapa));
marker.setDraggable(true);
marker.setTitle("DADOS");
marker.setSnippet(center.getLatitude()+ "," + center.getLongitude());
marker.setSubDescription("subDescription Marker");
marker.setInfoWindow(new CustomMarkerInfoWindow(osm));
marker.setInfoWindowAnchor(marker.ANCHOR_CENTER, marker.ANCHOR_TOP);
marker.setOnMarkerClickListener(new Marker.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker m, MapView mapView) {
Log.i("Script","onMarkerClick");
m.showInfoWindow();
InfoWindow.getOpenedInfoWindowsOn(osm);
return true;
}
});
marker.setOnMarkerDragListener(new Marker.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
Log.i("Script", "onMarkerDragStart()");
}
#Override
public void onMarkerDragEnd(Marker marker) {
Log.i("Script", "onMarkerDragEnd()");
}
#Override
public void onMarkerDrag(Marker marker) {
Log.i("Script", "onMarkerDrag()");
}
});
// osm.getOverlays().clear();
osm.getOverlays().add(new MapOverlay(this));
osm.getOverlays().add(marker);
osm.invalidate();
}
public void onResume(){
super.onResume();
//this will refresh the osmdroid configuration on resuming.
//if you make changes to the configuration, use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
osm.onResume(); //needed for compass, my location overlays, v6.0.0 and up
}
public void onPause(){
super.onPause();
//this will refresh the osmdroid configuration on resuming.
//if you make changes to the configuration, use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Configuration.getInstance().save(this, prefs);
osm.onPause(); //needed for compass, my location overlays, v6.0.0 and up
}
#Override
public void onLocationChanged(Location location) {
GeoPoint center = new GeoPoint(location.getLatitude(), location.getLongitude());
mc.animateTo(center);
addMarker(center);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onDestroy() {
super.onDestroy();
if (locationManager != null) {
locationManager.removeUpdates((LocationListener) this);
}
}
class MapOverlay extends Overlay {
public MapOverlay(Context ctx) {
super(ctx);
}
#Override
public void draw(Canvas c, MapView osmv, boolean shadow) {
}
// aqui é onde movimenta o cursor do mapa
#Override
public boolean onSingleTapConfirmed(MotionEvent me, MapView mv) {
Projection p = osm.getProjection();
GeoPoint gp = (GeoPoint) p.fromPixels((int) me.getX(), (int) me.getY());
addMarker(gp);
return (true); // se false ---> vai travar o mapa
}
}
// Aqui quando eu pressionar em uma determinada parte do mapa ele
// irá mostrar as minhas cordenadas
#Override
public boolean singleTapConfirmedHelper(GeoPoint p) {
Toast.makeText(this, "Coordenadas:\nLatitude: ("+p.getLatitude() +"\nLongitude: " +
""+p.getLongitude()+")" , Toast.LENGTH_SHORT).show();
// InfoWindow.closeAllInfoWindowsOn(osm); //Clicando em qualquer canto da tela, fecha o infowindow
return (true);
}
//Aqui eu adiciono uma marcação se eu pressionar a tela
#Override
public boolean longPressHelper(GeoPoint p) {
// addMarker(p);
return true;
}
// InfoWindow
public class CustomMarkerInfoWindow extends MarkerInfoWindow {
public CustomMarkerInfoWindow(MapView mapView) {
super(R.layout.bonuspack_bubble,mapView);
}
#Override
public void onOpen(Object item){
Marker m = (Marker) item;
ImageView iv = (ImageView) mView.findViewById(R.id.bubble_image);
iv.setImageResource(R.drawable.btn_moreinfo);
TextView snippet = (TextView) mView.findViewById(R.id.bubble_title);
snippet.setText(m.getTitle());
TextView coordenada = (TextView) mView.findViewById(R.id. coordenadas);
coordenada.setText(m.getSnippet());
Button bt = (Button) mView.findViewById(R.id.bubble_buttom);
bt.setVisibility(View.VISIBLE);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"Salvo",Toast.LENGTH_SHORT ).show();
}
});
}
}
}
The results I got trying to implement geojson were not satisfactory. I saw several tutorials, but none explained whether or not I had to implement a public void method, if I would have to put it inside the onCreate method, or if I would have to create one Java file.
How can I do this?
You should find most of what you need in OSMBonusPack GeoJSON features.
But this is assuming you have the right level of skills about Java and Android development.

GPS-Service , Main Activity and Map Activity (Pass co-ordinates from service to map current location)

I am new to android and try to implement an activity with two tab one show co-ordinates which i got from GPS-Service and i want to mark that current location (co-ordinates value using marker) in map using coordinates value which i got from GPS services. And kindly help me for implementing Geo Fencing in map also.
GPS Service
package com.app.servicegps;
/**
* Created by Android on 29-Dec-16.
*/
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
public class GPS_Service extends Service {
private LocationListener listener;
private LocationManager locationManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("coordinatesLongt",location.getLongitude());
i.putExtra("coordinatesLangt",location.getLatitude());
sendBroadcast(i);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);
}
#Override
public void onDestroy() {
super.onDestroy();
if(locationManager != null){
//noinspection MissingPermission
locationManager.removeUpdates(listener);
}
}
}
Map Activity
package com.app.servicegps;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements LocationListener,OnMapReadyCallback,
SensorEventListener, DialogInterface.OnClickListener {
private GoogleMap mMap;
private BroadcastReceiver broadcastReceiver;
Marker now;
String langt = null;
String longt= null;
#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);
}
#Override
public void onLocationChanged(Location location) {
if(now != null){
now.remove();
}
//TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
//double latitude = location.getLatitude();
// Getting longitude of the current location
// double longitude = location.getLongitude();
double latitude= Double.parseDouble(langt);
double longitude= Double.parseDouble(longt);
// Creating a LatLng object for the current location
// LatLng latLng = new LatLng(latitude, longitude);
LatLng latLng = new LatLng(latitude, longitude);
now = mMap.addMarker(new MarkerOptions().position(latLng));
// Showing the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null){
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//get value
if(intent.getAction().equals("location_update"))
{
langt=intent.getStringExtra("coordinatesLangt");
longt=intent.getStringExtra("coordinatesLongt");
}
}
};
}
registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
}
/**
* 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 sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
#Override
public void onSensorChanged(SensorEvent event) {
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
Main Activity
package com.app.servicegps;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button btn_start, btn_stop;
private TextView textView;
private BroadcastReceiver broadcastReceiver;
#Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null){
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
textView.append("\n" +intent.getExtras().get("coordinates"));
}
};
}
registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
}
#Override
protected void onDestroy() {
super.onDestroy();
if(broadcastReceiver != null){
unregisterReceiver(broadcastReceiver);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.button);
btn_stop = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.textView);
if(!runtime_permissions())
enable_buttons();
}
private void enable_buttons() {
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i =new Intent(getApplicationContext(),GPS_Service.class);
startService(i);
}
});
btn_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),GPS_Service.class);
stopService(i);
}
});
}
private boolean runtime_permissions() {
if(Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},100);
return true;
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 100){
if( grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
enable_buttons();
}else {
runtime_permissions();
}
}
}
}
Kindly help me for Geo fencing how i implement it it map activity.
The basic this i want is a main activity with tabs fragments.
Fragment 1st - Show Coordinates
Fragment 2nd Show Map
And A Geo Fencing To Show Notification when i enter in a tag place.
Interface class
public interface LocationInter {
void onUpdateLocation(Location location);
}
Implement the interface in main activity.
Add below lines in GPS service class.
private static LocationInter locationListener = null;
public void LocationInstance(LocationGuideInter locationListeners) {
if (locationListener == null) {
locationListener = locationListeners;
}
}
In Location change add this line
if (locationListener != null) {
locationListener.onUpdateLocation(location);
}
This is taken from android documentation so you can look at more details here
Set up for Geofence Monitoring
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Create geofence objects
Use Geofence.Builder to create a geofence, setting the desired radius, duration, and transition types for the geofence. For example, to populate a list object named mGeofenceList:
mGeofenceList.add(new Geofence.Builder()
// Set the request ID of the geofence. This is a string to identify this
// geofence.
.setRequestId(entry.getKey())
.setCircularRegion(
entry.getValue().latitude,
entry.getValue().longitude,
Constants.GEOFENCE_RADIUS_IN_METERS
)
.setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
.build());
Specify geofences and initial triggers
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
}
Define an Intent for geofence transitions
public class MainActivity extends FragmentActivity {
...
private PendingIntent getGeofencePendingIntent() {
// Reuse the PendingIntent if we already have it.
if (mGeofencePendingIntent != null) {
return mGeofencePendingIntent;
}
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
// We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
// calling addGeofences() and removeGeofences().
return PendingIntent.getService(this, 0, intent, PendingIntent.
FLAG_UPDATE_CURRENT);
}
Add geofences
public class MainActivity extends FragmentActivity {
...
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent()
).setResultCallback(this);
}
Handle Geofence Transitions
public class GeofenceTransitionsIntentService extends IntentService {
protected void onHandleIntent(Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
String errorMessage = GeofenceErrorMessages.getErrorString(this,
geofencingEvent.getErrorCode());
Log.e(TAG, errorMessage);
return;
}
// Get the transition type.
int geofenceTransition = geofencingEvent.getGeofenceTransition();
// Test that the reported transition was of interest.
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
// Get the geofences that were triggered. A single event can trigger
// multiple geofences.
List triggeringGeofences = geofencingEvent.getTriggeringGeofences();
// Get the transition details as a String.
String geofenceTransitionDetails = getGeofenceTransitionDetails(
this,
geofenceTransition,
triggeringGeofences
);
// Send notification and log the transition details.
sendNotification(geofenceTransitionDetails);
Log.i(TAG, geofenceTransitionDetails);
} else {
// Log the error.
Log.e(TAG, getString(R.string.geofence_transition_invalid_type,
geofenceTransition));
}
}
Geofences tutorial from Raywendrlich here

Google Places Autocomplete API crashed on some phones

I am trying to implement Google Places Autocomplete API, but the search bar for it crashed on some phones every time when I search for something.
It does work on some phones (like Moto G 2nd Generation XT1068) but crashes on Lenovo A7000 whenever I search anything in the search bar and then press enter.
Another problem I face is; I want to change the default google maps location that shows near South Africa. Change it to a specific location. How can I do that?
package com.docto365.activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
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.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.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import com.docto365.R;
public class HospitalMapsActivity extends FragmentActivity /*implements OnMapReadyCallback*/ implements LocationListener{
private GoogleMap mMap;
LocationManager location;
Toolbar mActionBarToolbar;
private static final LatLngBounds Bhubaneswar = new LatLngBounds(
new LatLng(20.192597, 85.792239), new LatLng(20.409371, 85.824544));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hospital_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);*/
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setHint("Search Hospitals & Clinics");
autocompleteFragment.setBoundsBias(Bhubaneswar);
mActionBarToolbar=(Toolbar)findViewById(R.id.toolbar);
mActionBarToolbar.setTitle(" Hospitals & Clinics");
mActionBarToolbar.setNavigationIcon(R.drawable.ic_arrow_back);
mActionBarToolbar.setTitleTextColor(Color.WHITE);
mActionBarToolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
location= (LocationManager) getSystemService(Context.LOCATION_SERVICE);
location.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 400, 1000, this);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
//Log.i(TAG, "Place: " + place.getName());
//Toast.makeText(HospitalMapsActivity.this, "Place: " + place.getName(), Toast.LENGTH_LONG).show();
//EditText et = (EditText) findViewById(R.id.autotext);
//String destination = et.getText().toString();
String destination = (String) place.getName();
List<Address> addressList = null;
if (destination == null || !destination.equals("")) {
Geocoder geocoder = new Geocoder(HospitalMapsActivity.this);
try {
addressList = geocoder.getFromLocationName(destination, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title(destination));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
//Log.i(TAG, "An error occurred: " + status);
Toast.makeText(HospitalMapsActivity.this, "An error occured: " + status, Toast.LENGTH_LONG).show();
}
});
//setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded()
{
if(mMap==null)
mMap=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if(mMap!=null)
setUpMap();
}
private void setUpMap()
{
//mMap.addMarker(new MarkerOptions().position(new LatLng(20.271790,85.843858)).title("Marker").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
mMap.setMyLocationEnabled(true);
//mMap.animateCamera( CameraUpdateFactory.zoomTo( 17.0f ) );
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(HospitalMapsActivity.this,"Tap on healthcare centre name to book a cab",Toast.LENGTH_LONG).show();
return false;
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
AlertDialog.Builder dialog = new AlertDialog.Builder(HospitalMapsActivity.this);
dialog.setTitle("Book Cab");
dialog.setMessage("Do you want to book a cab?"/*HospitalMapsActivity.this.getResources().getString(R.string.gps_network_not_enabled)*/);
dialog.setPositiveButton("Book now"/*HospitalMapsActivity.this.getResources().getString(R.string.open_location_settings)*/, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent i = new Intent(HospitalMapsActivity.this, Book.class);
startActivity(i);
//get gps
}
});
dialog.setNegativeButton("Later"/*HospitalMapsActivity.this.getResources().getString(R.string.open_location_settings)*/, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
//get gps
}
});
dialog.show();
}
});
LocationManager lm = (LocationManager)HospitalMapsActivity.this.getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch(Exception ex) {
Toast.makeText(HospitalMapsActivity.this,"Something is wrong",Toast.LENGTH_LONG).show();
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {
Toast.makeText(HospitalMapsActivity.this,"Something is wrong",Toast.LENGTH_LONG).show();
}
if(gps_enabled==false /*&& network_enabled==false*/) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(HospitalMapsActivity.this);
dialog.setTitle("Location Services Disabled");
dialog.setMessage("Please enable location services."/*HospitalMapsActivity.this.getResources().getString(R.string.gps_network_not_enabled)*/);
dialog.setPositiveButton("Enable"/*HospitalMapsActivity.this.getResources().getString(R.string.open_location_settings)*/, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
HospitalMapsActivity.this.startActivity(myIntent);
//get gps
}
});
dialog.show();
}
mMap.addMarker(new MarkerOptions().position(new LatLng(20.260423, 85.777747)).title("AMRI HOSPITALS").icon(BitmapDescriptorFactory.fromResource(R.drawable.sp)));
}
#Override
public void onLocationChanged(Location arg0) {
LatLng latLng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15.0f);
mMap.animateCamera(cameraUpdate);
location.removeUpdates(this);
setUpMapIfNeeded();
//mMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(20.269556,85.841157) , 14.0f) );
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
To address your problems:
It does work on some phones (like Moto G 2nd Generation XT1068) but crashes on Lenovo A7000 whenever I search anything in the search bar and then press enter.
Please check the following:
Check if your Android platform is included in supported versions given in Android guide.
As mentioned in Google Places API - Troubleshooting, majority of the errors that your app is likely to experience are usually caused by configurations error. To get the status message for the errors that occur , call PlaceAutocomplete.getStatus() in onActivityResult() callback.
In using Place Autocomplete, please check if autocomplete is properly added to your app, as given in Place Autocomplete, using the following ways:
Add an autocomplete widget
Get place predictions programmatically
You may also check the given workaround in this GitHub post - Google Places Autocomplete does not work on mobile wherein a relevant code was placed into a function and then used the ng-focus directive to execute the expression on the desired element like:
<input id="searchBar" type="text" placeholder="Search" ng-focus="disableTap()">
Another problem I face is; I want to change the default google maps location that shows near South Africa. Change it to a specific location. How can I do that?
To change default google maps location and to get precise results, try given steps in Update your location on Google wherein you can:
Turn your location on or off, and
Check and update your location
For more information, please try going through the given documentations.
I hope one works for you.

How to display a Dialog fragment inside location listener to trigger another activity

I have an app location listener which pops up toast alerts when the user gets within a specified distance of any point in a list. Instead of a toast popup I'd like to call a dialog fragment that, when the user selects yes, transfers the user into a quiz activity which asks them a question based on their location.
In short I want to be able to display this dialog fragment, instead of the toast, in my location listener activity. Thus far I have tried
DialogFragment dialog = new LocationDialog();
showDialog(dialog);
in place of the toast alert but I get the error "The method showDialog(DialogFragment) is undefined for the type QLocationListener. I've been going around in circles following various tutorials, guides and Google's android documentation without avail so some guidance would be greatly appreciated.
All my code is functioning as standalone apps I'm just struggling to link the location listener + main activity to the quiz via the dialog fragment. I also hope to be able to pass location information to the quiz in a bundle so it knows which question and answers to display but that's a task for another day...
Main Activity
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.location.LocationManager;
import android.os.Bundle;
public class MainActivity extends Activity {
private static final long MINIMUM_DISTANCECHANGE_FOR_UPDATE = 1;
private static final long MINIMUM_TIME_BETWEEN_UPDATE = 1000;
private LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
QLocationListener qLL = new QLocationListener();
qLL.parentActivity = this;
// create the hard-coded list of points of interest
ArrayList<QuizContent> pointList = new ArrayList<QuizContent>();
// ExampleA
QuizContent MapPoint = new QuizContent(25,5, "example question?", "a", "b","c","d", "a");
// ExampleB
QuizContent MapPoint2 = new QuizContent(26,5, "example question?", "a", "b","c","d", "a");
// ExampleC
QuizContent MapPoint3 = new QuizContent(27,5, "example question?", "a", "b","c","d", "a");
pointList.add(MapPoint);
pointList.add(MapPoint2);
pointList.add(MapPoint3);
// now set up the location manager and listener
qLL.pointList = pointList;
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATE,
MINIMUM_DISTANCECHANGE_FOR_UPDATE,
qLL
);
}
}
QLocation Listener
import java.util.ArrayList;
import android.app.AlertDialog;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.widget.Toast;
import android.widget.TextView;
public class QLocationListener implements LocationListener {
public MainActivity parentActivity ;
// this is my list of quiz content (questions, answers, locations)
public ArrayList<QuizContent> pointList;
// this method is called when the location is changed
public void onLocationChanged(Location location) {
// now measure distance from all locations in quiz list
for (int i=0;i<pointList.size();i++){
QuizContent gp = pointList.get(i);
Location fixedLoc = new Location("one");
Double lat = Double.valueOf(String.valueOf(gp.getLatitude()));
Double lng = Double.valueOf(String.valueOf(gp.getLongitude()));
fixedLoc.setLatitude(lat);
fixedLoc.setLongitude(lng);
Log.i("location",lat+" "+location.getLatitude());
Log.i("location",lng+" "+location.getLongitude());
// calculate distance
float distance = location.distanceTo(fixedLoc);
if (i == 0) { // this is location a
if (distance < 10) {
DialogFragment dialog = new LocationDialog();
showDialog(dialog);
}
}
if (i == 1) { // this is location b
if (distance < 10) {
Toast.makeText(parentActivity.getBaseContext(),
"Welcome to location b", Toast.LENGTH_LONG).show();
}
}
if (i == 3) { // this is location c
if (distance < 10) {
Toast.makeText(parentActivity.getBaseContext(),
"Welcome to location c", Toast.LENGTH_LONG).show();
}
}
}
}
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
Dialog Fragment
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public class LocationDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setMessage("Quiz Location Found, answer the question?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(getActivity(), Quiz.class));
// take the quiz!
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return alertDialog.create();
}
}
You need to call showDialog on Activity/App context
Try:
From activity:
QLocationListener qLocationListener= new QLocationListener(this)
In QLocationListener:
Activity act;
QLocationListener(Activity a)
{
//Constructor
act=a;
}
and then finally where you call showDialog:
act.showDialog(dialog);

blank screen after back press google map api v2

I have a map named MapActivity which operated from
activity.MapActivity extends from fragment.Map loaded first time
successfully.When i am going for other fragment from activity.After
this when i pressed back button for map,map is showing blank
screen.Any idea?
MapActivity
package com.example.map;
import updatedata.FindMapDataService;
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.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class MapActivity extends Fragment implements OnMyLocationChangeListener {
public GoogleMap gmap;
public static double maillat,maillng,latitude,longitude,elat5,elng5;
public static String flat5,flng5;
public static int s,state,check;
public static long utime,ftime;
View view;
public static Runnable runn;
public static Handler handler;
public boolean wifi,gps,network,val,inter;
public void onCreate(Bundle savedInstanceState) {
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// location data find from MainActivitiy
elat5=MainActivity.lat10;
elng5=MainActivity.lng10;
// location data find from LocationFindactivity
flat5=LocationFindActivity.latt;
flng5=LocationFindActivity.lng;
// find status for opening map
s=MainActivity.status;
// find time for handler
if(ftime == 0){
ftime=15000;
}
// Load Preferences
LoadPreferences();
//get view
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try{
view = inflater.inflate(R.layout.map, container, false);
}catch(InflateException e){
e.printStackTrace();
}
//Check location data source
if(s==1){
initializemailmap();
check=1;
Log.e("Activity","link");
}else if(s==2){
elat5=Double.parseDouble(flat5);
elng5=Double.parseDouble(flng5);
check=1;
initializemailmap();
Log.e("Activity","Find");
}else{
initializemap();
check=0;
Log.e("Activity","Normal");
}
if( check == 1){
getActivity().startService(new Intent(getActivity(),FindMapDataService.class));
handler = new Handler();
handler.postDelayed(runn, 10000);
}
runn = new Runnable() {
#Override
public void run() {
flat5=FindMapDataService.latt;
flng5=FindMapDataService.lng;
if(flat5 != null && flng5 != null){
elat5=Double.parseDouble(flat5);
elng5=Double.parseDouble(flng5);
createMailMap();
}
// createMailMap();
handler.postDelayed(this, ftime);
}
};
// Show current location
gmap.setMyLocationEnabled(true);
if(check == 0){
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
double glat = location.getLatitude();
double glng = location.getLongitude();
CameraUpdate myLoc = CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder().target(new LatLng(glat,glng)).zoom(12).build());
gmap.moveCamera(myLoc);
}
return view;
}
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
double lat=arg0.getLatitude();
double lng=arg0.getLongitude();
CameraUpdate myLoc = CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder().target(new LatLng(lat,lng)).zoom(15).build());
gmap.moveCamera(myLoc);
gmap.setOnMyLocationChangeListener(null);
}
//after mail initialisation
private void initializemailmap() {
// TODO Auto-generated method stub
if(gmap == null){
Fragment ft=getFragmentManager().findFragmentById(R.id.mymap);
gmap=((SupportMapFragment) ft).getMap();
createMailMap();
} else{
createMailMap();
Log.e("Find","Create Mail Map");
}
}
//Normal initialisation
private void initializemap() {
// TODO Auto-generated method stub
if(gmap == null){
Fragment ft1=getFragmentManager().findFragmentById(R.id.mymap);
gmap=((SupportMapFragment) ft1).getMap();
}
if (gmap == null) {
Toast.makeText(getActivity(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
private void createMailMap() {
// TODO Auto-generated method stub
maillat=elat5;
// Log.e("latBrowser", Double.toString(latitude));
maillng=elng5;
// Create a LatLng object for the current location
LatLng latLng = new LatLng(maillat, maillng);
// Show the current location in Google Map
gmap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Set zooming control on goole to view location
gmap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));
//Add marker at current position
MarkerOptions marker=new MarkerOptions();
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.arr));
//marker.position(latLng).anchor(1,1).rotation(90);
gmap.addMarker(marker.position(new LatLng(maillat, maillng)).title("You are here!"));
//Remove default marker
// gmap.clear();
}
//save preferences
private void SavePreferences(){
SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE );
SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putInt("val", state);
editor.putLong("time", utime);
editor.commit();
}
//load preferences
private void LoadPreferences(){
SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
// mapstatus = sharedPreferences.getInt("val",1);
ftime=sharedPreferences.getLong("time", 1);
}
public void onResume(){
super.onResume();
}
public void onStop(){
super.onStop();
SavePreferences();
gmap = null;
}
public void onDestroyView() {
super.onDestroyView();
Fragment f = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.mymap);
if (f != null){
getFragmentManager().beginTransaction().remove(f).commitAllowingStateLoss();
}
}
public void onDestroy(){
super.onDestroy();
MainActivity.status=0;
if(check == 1){
getActivity().stopService(new Intent(getActivity(),FindMapDataService.class));
}
SavePreferences();
}
}
you need to destroy map when you are using map inside Fragment
public void onDestroy(){
gmap = null;
super.onDestroy();
MainActivity.status=0;
if(check == 1){
getActivity().stopService(new Intent(getActivity(),FindMapDataService.class));
}
SavePreferences();
}
also update in OnCreateView method
...
//Check location data source
initializemailmap();
if(s==1){
check=1;
Log.e("Activity","link");
}else if(s==2){
elat5=Double.parseDouble(flat5);
elng5=Double.parseDouble(flng5);
check=1;
initializemailmap();
Log.e("Activity","Find");
}else{
initializemap();
check=0;
Log.e("Activity","Normal");
}
...
this code from your OnCreateView menthod
i hope it helps.
In my case I changed getFragmentManager().beginTransaction() with getChildFragmentManager().beginTransaction() and everything works fine now.

Categories

Resources