I'm trying to use the mapbox SDK to get my current location and set the navigation, but it's not working. I was trying to implement this code following the tutorial from the mapbox website.
public class pos extends AppCompatActivity implements LocationEngineListener, PermissionsListener {
private MapView mapView;
// variables for adding location layer
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationLayerPlugin locationPlugin;
private LocationEngine locationEngine;
private Location originLocation;
// variables for adding a marker
private Marker destinationMarker;
private LatLng originCoord;
private LatLng destinationCoord;
// variables for calculating and drawing a route
private Point originPosition;
private Point destinationPosition;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
//private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,"pk.eyJ1IjoiaWhkaW5hIiwiYSI6ImNqaDRveHdhcjB1ZTIyd253M2R2MGhwY28ifQ.If9oJq_rILeuaK1sjp9-nw");
setContentView(R.layout.activity_pos);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
enableLocationPlugin();
originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
mapboxMap.addOnMapClickListener(new MapboxMap.OnMapClickListener() {
#Override
public void onMapClick(#NonNull LatLng point) {
if (destinationMarker != null) {
mapboxMap.removeMarker(destinationMarker);
}
destinationCoord = point;
destinationMarker = mapboxMap.addMarker(new MarkerOptions()
.position(destinationCoord)
);
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
/* button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);*/
}
;
});
/*button = findViewById(R.id.startButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Point origin = originPosition;
Point destination = destinationPosition;
// Pass in your Amazon Polly pool id for speech synthesis using Amazon Polly
// Set to null to use the default Android speech synthesizer
String awsPoolId = null;
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.origin(origin)
.destination(destination)
.awsPoolId(awsPoolId)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(NavigationActivity.this, options);
}
});*/
}
;
});
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder()
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Create an instance of LOST location engine
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(true);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings( {"MissingPermission"})
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationPlugin();
} else {
finish();
}
}
#Override
#SuppressWarnings( {"MissingPermission"})
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
originLocation = location;
setCameraPosition(location);
locationEngine.removeLocationEngineListener(this);
}
}
#Override
#SuppressWarnings( {"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStop();
}
mapView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
Try modifying your methods with this:
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(true);
locationPlugin.setCameraMode(CameraMode.TRACKING);
locationPlugin.setRenderMode(RenderMode.COMPASS);
getLifecycle().addObserver(locationPlugin);
Log.e(TAG, "enableLocationPlugin:Permission Granted" );
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
Log.e(TAG, "enableLocationPlugin:Permission Not Granted" );
}
}
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.addLocationEngineListener(this);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
and your onStart with this:
#Override
#SuppressWarnings({"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
locationEngine.addLocationEngineListener(this);
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}
Related
I'm developing a taxi application. The only problem is my marker doesn't update it's location screamingly on mapview. After some debugging I noticed that the listener named onLocationChanged is never called!!!
The idea is to view a marker on mapview to view driver's location and track is own location while driver. But, the problem is his marker never changes!.
Here is my code:
public class HomeFragment extends FragmentManagePermission implements OnMapReadyCallback, DirectionCallback, Animation.AnimationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
public String NETWORK;
public String ERROR = "حدث خطأ";
public String TRYAGAIN;
Boolean flag = false;
GoogleMap myMap;
ImageView current_location, clear;
MapView mMapView;
int i = 0;
String result = "";
Animation animFadeIn, animFadeOut;
String TAG = "home";
LinearLayout linear_request;
String permissionAsk[] = {
PermissionUtils.Manifest_CAMERA,
PermissionUtils.Manifest_WRITE_EXTERNAL_STORAGE,
PermissionUtils.Manifest_READ_EXTERNAL_STORAGE,
PermissionUtils.Manifest_ACCESS_FINE_LOCATION,
PermissionUtils.Manifest_ACCESS_COARSE_LOCATION
};
CardView rides, earnings;
private String driver_id = "";
private String cost = "";
private String unit = "";
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Double currentLatitude;
private Double currentLongitude;
private View rootView;
private String check = "";
private String drivername = "";
private Marker my_marker;
private boolean isShown = true;
private FusedLocationProviderClient fusedLocationProviderClient;
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fusedLocationProviderClient = new FusedLocationProviderClient(requireContext());
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
NETWORK = getString(R.string.network_not_available);
TRYAGAIN = getString(R.string.tryagian);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
try {
rootView = inflater.inflate(R.layout.home_fragment, container, false);
// globatTitle = "Home";
((HomeActivity) getActivity()).fontToTitleBar(getString(R.string.home));
bindView(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
askCompactPermissions(permissionAsk, new PermissionResult() {
#Override
public void permissionGranted() {
if (!GPSEnable()) {
tunonGps();
} else {
getCurrentlOcation();
}
}
#Override
public void permissionDenied() {
}
#Override
public void permissionForeverDenied() {
openSettingsApp(getActivity());
}
});
} else {
if (!GPSEnable()) {
tunonGps();
} else {
getCurrentlOcation();
}
}
} catch (Exception e) {
Log.e("tag", "Inflate exception " + e.toString());
}
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1000) {
if (resultCode == Activity.RESULT_OK) {
String result = data.getStringExtra("result");
getCurrentlOcation();
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
#Override
public void onPause() {
super.onPause();
try {
if (getActivity() != null && mMapView != null) {
mMapView.onPause();
}
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
} catch (Exception e) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
if (mMapView != null) {
mMapView.onDestroy();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
try {
if (mMapView != null) {
mMapView.onSaveInstanceState(outState);
}
} catch (Exception e) {
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
try {
if (mMapView != null) {
mMapView.onLowMemory();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStop() {
super.onStop();
try {
if (mMapView != null) {
mMapView.onStop();
}
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
} catch (Exception e) {
}
}
#Override
public void onResume() {
super.onResume();
try {
if (mMapView != null) {
mMapView.onResume();
}
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
} catch (Exception e) {
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onMapReady(GoogleMap googleMap) {
myMap = googleMap;
myMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(final Marker marker) {
View v = null;
if (getActivity() != null) {
v = getActivity().getLayoutInflater().inflate(R.layout.view_custom_marker, null);
TextView title = (TextView) v.findViewById(R.id.t);
TextView t1 = (TextView) v.findViewById(R.id.t1);
TextView t2 = (TextView) v.findViewById(R.id.t2);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "font/AvenirLTStd_Medium.otf");
t1.setTypeface(font);
t2.setTypeface(font);
String name = marker.getTitle();
title.setText(name);
String info = marker.getSnippet();
t1.setText(info);
driver_id = (String) marker.getTag();
drivername = marker.getTitle();
}
return v;
}
});
if (myMap != null) {
tunonGps();
}
}
#Override
public void onDirectionSuccess(Direction direction, String rawBody) {
}
#Override
public void onDirectionFailure(Throwable t) {
}
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
public void bindView(Bundle savedInstanceState) {
MapsInitializer.initialize(this.getActivity());
mMapView = (MapView) rootView.findViewById(R.id.mapview);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
// load animations
animFadeIn = AnimationUtils.loadAnimation(getActivity(),
R.anim.dialogue_scale_anim_open);
animFadeOut = AnimationUtils.loadAnimation(getActivity(),
R.anim.dialogue_scale_anim_exit);
animFadeIn.setAnimationListener(this);
animFadeOut.setAnimationListener(this);
rides = (CardView) rootView.findViewById(R.id.cardview_totalride);
earnings = (CardView) rootView.findViewById(R.id.earnings);
Utils.overrideFonts(getActivity(), rootView);
getEarningInfo();
}
public void getEarningInfo() {
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
progressDialog.show();
RequestParams params = new RequestParams();
if (Utils.haveNetworkConnection(getActivity())) {
params.put("driver_id", SessionManager.getUserId());
}
Server.setHeader(SessionManager.getKEY());
Server.get(Server.EARN, params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("earn", response.toString());
try {
if (response.has("status") && response.getString("status").equalsIgnoreCase("success")) {
if (response.getJSONObject("data").getJSONObject("request").length() != 0) {
Gson gson = new Gson();
PendingRequestPojo pojo = gson.fromJson(response.getJSONObject("data").getJSONObject("request").toString(), PendingRequestPojo.class);
((HomeActivity) getActivity()).setPojo(pojo);
((HomeActivity) getActivity()).setStatus(pojo, "", false);
}
String today_earning = response.getJSONObject("data").getString("today_earning");
String week_earning = response.getJSONObject("data").getString("week_earning");
String total_earning = response.getJSONObject("data").getString("total_earning");
String total_rides = response.getJSONObject("data").getString("total_rides");
try {
String unit = response.getJSONObject("data").getString("unit");
//SessionManager.getInstance().setUnit(unit);
} catch (JSONException e) {
}
TextView textView_today = (TextView) rootView.findViewById(R.id.txt_todayearning);
TextView textView_week = (TextView) rootView.findViewById(R.id.txt_weekearning);
TextView textView_overall = (TextView) rootView.findViewById(R.id.txt_overallearning);
TextView textView_totalride = (TextView) rootView.findViewById(R.id.txt_total_ridecount);
textView_today.setText(today_earning);
textView_week.setText(week_earning);
textView_overall.setText(total_earning);
textView_totalride.setText(total_rides);
} else {
Toast.makeText(getActivity(), response.getString("data"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getActivity(), getString(R.string.error_occurred), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFinish() {
super.onFinish();
if (progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
#SuppressWarnings({"MissingPermission"})
#Override
public void onConnected(#Nullable Bundle bundle) {
try {
android.location.Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
if (myMap != null) {
myMap.clear();
my_marker = myMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Your are here."));
my_marker.showInfoWindow();
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 15);
myMap.animateCamera(cameraUpdate);
myMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
if (isShown) {
isShown = false;
rides.startAnimation(animFadeOut);
rides.setVisibility(View.GONE);
earnings.startAnimation(animFadeOut);
earnings.setVisibility(View.GONE);
} else {
isShown = true;
rides.setVisibility(View.VISIBLE);
rides.startAnimation(animFadeIn);
earnings.setVisibility(View.VISIBLE);
earnings.startAnimation(animFadeIn);
}
}
});
}
setCurrentLocation(currentLatitude, currentLongitude);
}
} catch (Exception e) {
}
}
public void setCurrentLocation(final Double lat, final Double log) {
try {
my_marker.setPosition(new LatLng(lat, log));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 15);
myMap.animateCamera(cameraUpdate);
RequestParams par = new RequestParams();
Server.setHeader(SessionManager.getKEY());
par.put("user_id", SessionManager.getUserId());
par.add("latitude", String.valueOf(currentLatitude));
par.add("longitude", String.valueOf(currentLongitude));
Server.post(Server.UPDATE, par, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
}
});
} catch (Exception e) {
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
}
#Override
public void onLocationChanged(android.location.Location location) {
if (location != null) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
if (!currentLatitude.equals(0.0) && !currentLongitude.equals(0.0)) {
setCurrentLocation(currentLatitude, currentLongitude);
} else {
Toast.makeText(getActivity(), getString(R.string.couldnt_get_location), Toast.LENGTH_LONG).show();
}
}
}
public void getCurrentlOcation() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
}
public void tunonGps() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
// **************************
builder.setAlwaysShow(true); // this is the key ingredient
// **************************
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result
.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can
// initialize location
// requests here.
getCurrentlOcation();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be
// fixed by showing the user
// a dialog.
try {
// Show the dialog by calling
// startResolutionForResult(),
// and checkky the result in onActivityResult().
status.startResolutionForResult(getActivity(), 1000);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have
// no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
}
public Boolean GPSEnable() {
GPSTracker gpsTracker = new GPSTracker(getActivity());
if (gpsTracker.canGetLocation()) {
return true;
} else {
return false;
}
}
}
What's the problem with my code?
As title says, I am trying to preview the two rear cameras on my phone on two separate textureviews. What I can do is preview the front camera and any of the rear cameras, but when I try to preview both rear cameras I get an "ERROR_MAX_CAMERAS_IN_USE" from the onError state callback method for the last-opened camera. By searching on the Internet and on here I couldn't really find any pointers on what I'm doing wrong.
For completeness here's the code of my main activity java class, in which I setup the cameras and obtain the previews:
public class MainActivity extends AppCompatActivity {
private final TextureView[] textureViews = new TextureView[2];
protected CameraDevice[] cameraDevices = new CameraDevice[2];
protected CameraCaptureSession[] cameraCaptureSessions = new CameraCaptureSession[2];
protected CaptureRequest.Builder[] captureRequestBuilders = new CaptureRequest.Builder[2];
private Size imageDimension;
private static final int REQUEST_CAMERA_PERMISSION = 200;
private final Handler[] mBackgroundHandlers = new Handler[2];
private final HandlerThread[] mBackgroundThreads = new HandlerThread[2];
private final int[] cameraIDs = {0, 2};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textureViews[0] = findViewById(R.id.left);
textureViews[1] = findViewById(R.id.right);
assert textureViews[0] != null;
assert textureViews[1] != null;
textureViews[0].setSurfaceTextureListener(textureListener0);
textureViews[1].setSurfaceTextureListener(textureListener1);
}
TextureView.SurfaceTextureListener textureListener0 = new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
openCamera(0);
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { }
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) { }
};
TextureView.SurfaceTextureListener textureListener1 = new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
openCamera(1);
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { }
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) { }
};
private final CameraDevice.StateCallback stateCallback0 = new CameraDevice.StateCallback() {
#Override
public void onOpened(CameraDevice camera) {
if(Debug.LOG) {
Log.e(Debug.TAG, camera.getId()+ " onOpened.");
}
cameraDevices[0] = camera;
createCameraPreview(0);
}
#Override
public void onDisconnected(CameraDevice camera) {
cameraDevices[0].close();
}
#Override
public void onError(CameraDevice camera, int error) {
cameraDevices[0].close();
cameraDevices[0] = null;
}
};
private final CameraDevice.StateCallback stateCallback1 = new CameraDevice.StateCallback() {
#Override
public void onOpened(CameraDevice camera) {
if(Debug.LOG) {
Log.e(Debug.TAG, camera.getId() + " onOpened.");
}
cameraDevices[1] = camera;
createCameraPreview(1);
}
#Override
public void onDisconnected(CameraDevice camera) {
cameraDevices[1].close();
}
#Override
public void onError(CameraDevice camera, int error) {
cameraDevices[1].close();
cameraDevices[1] = null;
}
};
protected void startBackgroundThreads() {
mBackgroundThreads[0] = new HandlerThread("Left camera Background");
mBackgroundThreads[0].start();
mBackgroundHandlers[0] = new Handler(mBackgroundThreads[0].getLooper());
mBackgroundThreads[1] = new HandlerThread("Right camera Background");
mBackgroundThreads[1].start();
mBackgroundHandlers[1] = new Handler(mBackgroundThreads[1].getLooper());
}
protected void stopBackgroundThreads() {
mBackgroundThreads[0].quitSafely();
mBackgroundThreads[1].quitSafely();
try {
mBackgroundThreads[0].join();
mBackgroundThreads[0] = null;
mBackgroundHandlers[0] = null;
mBackgroundThreads[1].join();
mBackgroundThreads[1] = null;
mBackgroundHandlers[1] = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void createCameraPreview(int cameraID) {
try {
SurfaceTexture texture = textureViews[cameraID].getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(imageDimension.getWidth(), imageDimension.getHeight());
Surface surface = new Surface(texture);
captureRequestBuilders[cameraID] = cameraDevices[cameraID].createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilders[cameraID].addTarget(surface);
cameraDevices[cameraID].createCaptureSession(Collections.singletonList(surface), new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession cameraCaptureSession) {
if (null == cameraDevices[cameraID]) {
return;
}
cameraCaptureSessions[cameraID] = cameraCaptureSession;
updatePreview(cameraID);
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession cameraCaptureSession) {
Toast.makeText(MainActivity.this, "Configuration change", Toast.LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void openCamera(int cameraID) {
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
if(Debug.LOG) {
Log.e(Debug.TAG, "openCamera " + cameraIDs[cameraID]);
}
try {
String cameraId = manager.getCameraIdList()[cameraIDs[cameraID]];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
assert map != null;
imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
// Add permission for camera and let user grant the permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
return;
}
manager.openCamera(cameraId, (cameraID == 0) ? stateCallback0 : stateCallback1, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
if(Debug.LOG) {
Log.e(Debug.TAG, "openCamera exited");
}
}
protected void updatePreview(int cameraID) {
if (null == cameraDevices[cameraID]) {
if(Debug.LOG) {
Log.e(Debug.TAG, "updatePreview error, return");
}
}
captureRequestBuilders[cameraID].set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
try {
cameraCaptureSessions[cameraID].setRepeatingRequest(captureRequestBuilders[cameraID].build(), null, mBackgroundHandlers[cameraID]);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void closeCamera(int cameraID) {
if (null != cameraDevices[cameraID]) {
cameraDevices[cameraID].close();
cameraDevices[cameraID] = null;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
finish();
}
}
}
#Override
protected void onResume() {
super.onResume();
startBackgroundThreads();
if(textureViews[0].isAvailable()) {
openCamera(0);
} else {
textureViews[0].setSurfaceTextureListener(textureListener0);
}
if(textureViews[1].isAvailable()) {
openCamera(1);
} else {
textureViews[1].setSurfaceTextureListener(textureListener1);
}
}
#Override
protected void onPause() {
closeCamera(0);
closeCamera(1);
stopBackgroundThreads();
super.onPause();
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am a Korean university student.
I use a translator.
Please excuse me for not being soft.
Failed to resolve issue while writing code, asking questions
Please help me.
The code below is quite simple and the only goal is to navigate from MainActivity.java to Mian2Activity.java However, I've been looking for a solution to this on a lot of tutorial and I really don't get what I'm doing wrong...
this is Main2Activity Code
public class Main2Activity extends AppCompatActivity
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleApiClient mGoogleApiClient = null;
private GoogleMap mGoogleMap = null;
private Marker currentMarker = null;
private static final String TAG = "googlemap_example";
private static final int GPS_ENABLE_REQUEST_CODE = 2001;
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 2002;
private static final int UPDATE_INTERVAL_MS = 1000; // 1초
private static final int FASTEST_UPDATE_INTERVAL_MS = 500; // 0.5초
private AppCompatActivity mActivity;
boolean askPermissionOnceAgain = false;
boolean mRequestingLocationUpdates = false;
Location mCurrentLocatiion;
boolean mMoveMapByUser = true;
boolean mMoveMapByAPI = true;
LatLng currentPosition;
LocationRequest locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL_MS)
.setFastestInterval(FASTEST_UPDATE_INTERVAL_MS);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate");
mActivity = this;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
Log.d(TAG, "onResume : call startLocationUpdates");
if (!mRequestingLocationUpdates) startLocationUpdates();
}
//앱 정보에서 퍼미션을 허가했는지를 다시 검사해봐야 한다.
if (askPermissionOnceAgain) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
askPermissionOnceAgain = false;
checkPermissions();
}
}
}
private void startLocationUpdates() {
if (!checkLocationServicesStatus()) {
Log.d(TAG, "startLocationUpdates : call showDialogForLocationServiceSetting");
showDialogForLocationServiceSetting();
}else {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "startLocationUpdates : 퍼미션 안가지고 있음");
return;
}
Log.d(TAG, "startLocationUpdates : call FusedLocationApi.requestLocationUpdates");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, this);
mRequestingLocationUpdates = true;
mGoogleMap.setMyLocationEnabled(true);
}
}
private void stopLocationUpdates() {
Log.d(TAG,"stopLocationUpdates : LocationServices.FusedLocationApi.removeLocationUpdates");
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mRequestingLocationUpdates = false;
}
#Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "onMapReady :");
mGoogleMap = googleMap;
//런타임 퍼미션 요청 대화상자나 GPS 활성 요청 대화상자 보이기전에
//지도의 초기위치를 서울로 이동
setDefaultLocation();
//mGoogleMap.getUiSettings().setZoomControlsEnabled(false);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
mGoogleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener(){
#Override
public boolean onMyLocationButtonClick() {
Log.d( TAG, "onMyLocationButtonClick : 위치에 따른 카메라 이동 활성화");
mMoveMapByAPI = true;
return true;
}
});
mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
Log.d( TAG, "onMapClick :");
}
});
mGoogleMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
#Override
public void onCameraMoveStarted(int i) {
if (mMoveMapByUser == true && mRequestingLocationUpdates){
Log.d(TAG, "onCameraMove : 위치에 따른 카메라 이동 비활성화");
mMoveMapByAPI = false;
}
mMoveMapByUser = true;
}
});
mGoogleMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
#Override
public void onCameraMove() {
}
});
}
#Override
public void onLocationChanged(Location location) {
currentPosition
= new LatLng( location.getLatitude(), location.getLongitude());
Log.d(TAG, "onLocationChanged : ");
String markerTitle = getCurrentAddress(currentPosition);
String markerSnippet = "위도:" + String.valueOf(location.getLatitude())
+ " 경도:" + String.valueOf(location.getLongitude());
//현재 위치에 마커 생성하고 이동
setCurrentLocation(location, markerTitle, markerSnippet);
mCurrentLocatiion = location;
}
#Override
protected void onStart() {
if(mGoogleApiClient != null && mGoogleApiClient.isConnected() == false){
Log.d(TAG, "onStart: mGoogleApiClient connect");
mGoogleApiClient.connect();
}
super.onStart();
}
#Override
protected void onStop() {
if (mRequestingLocationUpdates) {
Log.d(TAG, "onStop : call stopLocationUpdates");
stopLocationUpdates();
}
if ( mGoogleApiClient.isConnected()) {
Log.d(TAG, "onStop : mGoogleApiClient disconnect");
mGoogleApiClient.disconnect();
}
super.onStop();
}
#Override
public void onConnected(Bundle connectionHint) {
if ( mRequestingLocationUpdates == false ) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int hasFineLocationPermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (hasFineLocationPermission == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(mActivity,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
} else {
Log.d(TAG, "onConnected : 퍼미션 가지고 있음");
Log.d(TAG, "onConnected : call startLocationUpdates");
startLocationUpdates();
mGoogleMap.setMyLocationEnabled(true);
}
}else{
Log.d(TAG, "onConnected : call startLocationUpdates");
startLocationUpdates();
mGoogleMap.setMyLocationEnabled(true);
}
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed");
setDefaultLocation();
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended");
if (cause == CAUSE_NETWORK_LOST)
Log.e(TAG, "onConnectionSuspended(): Google Play services " +
"connection lost. Cause: network lost.");
else if (cause == CAUSE_SERVICE_DISCONNECTED)
Log.e(TAG, "onConnectionSuspended(): Google Play services " +
"connection lost. Cause: service disconnected");
}
public String getCurrentAddress(LatLng latlng) {
//지오코더... GPS를 주소로 변환
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(
latlng.latitude,
latlng.longitude,
1);
} catch (IOException ioException) {
//네트워크 문제
Toast.makeText(this, "지오코더 서비스 사용불가", Toast.LENGTH_LONG).show();
return "지오코더 서비스 사용불가";
} catch (IllegalArgumentException illegalArgumentException) {
Toast.makeText(this, "잘못된 GPS 좌표", Toast.LENGTH_LONG).show();
return "잘못된 GPS 좌표";
}
if (addresses == null || addresses.size() == 0) {
Toast.makeText(this, "주소 미발견", Toast.LENGTH_LONG).show();
return "주소 미발견";
} else {
Address address = addresses.get(0);
return address.getAddressLine(0).toString();
}
}
public boolean checkLocationServicesStatus() {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void setCurrentLocation(Location location, String markerTitle, String markerSnippet) {
mMoveMapByUser = false;
if (currentMarker != null) currentMarker.remove();
LatLng currentLatLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(currentLatLng);
markerOptions.title(markerTitle);
markerOptions.snippet(markerSnippet);
markerOptions.draggable(true);
//구글맵의 디폴트 현재 위치는 파란색 동그라미로 표시
//마커를 원하는 이미지로 변경하여 현재 위치 표시하도록 수정 fix - 2017. 11.27
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher));
currentMarker = mGoogleMap.addMarker(markerOptions);
if ( mMoveMapByAPI ) {
Log.d( TAG, "setCurrentLocation : mGoogleMap moveCamera "
+ location.getLatitude() + " " + location.getLongitude() ) ;
// CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(currentLatLng, 15);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(currentLatLng);
mGoogleMap.moveCamera(cameraUpdate);
}
}
public void setDefaultLocation() {
mMoveMapByUser = false;
//디폴트 위치, Seoul
LatLng DEFAULT_LOCATION = new LatLng(37.56, 126.97);
String markerTitle = "위치정보 가져올 수 없음";
String markerSnippet = "위치 퍼미션과 GPS 활성 요부 확인하세요";
if (currentMarker != null) currentMarker.remove();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(DEFAULT_LOCATION);
markerOptions.title(markerTitle);
markerOptions.snippet(markerSnippet);
markerOptions.draggable(true);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
currentMarker = mGoogleMap.addMarker(markerOptions);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(DEFAULT_LOCATION, 15);
mGoogleMap.moveCamera(cameraUpdate);
}
//여기부터는 런타임 퍼미션 처리을 위한 메소드들
#TargetApi(Build.VERSION_CODES.M)
private void checkPermissions() {
boolean fineLocationRationale = ActivityCompat
.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION);
int hasFineLocationPermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (hasFineLocationPermission == PackageManager
.PERMISSION_DENIED && fineLocationRationale)
showDialogForPermission("앱을 실행하려면 퍼미션을 허가하셔야합니다.");
else if (hasFineLocationPermission
== PackageManager.PERMISSION_DENIED && !fineLocationRationale) {
showDialogForPermissionSetting("퍼미션 거부 + Don't ask again(다시 묻지 않음) " +
"체크 박스를 설정한 경우로 설정에서 퍼미션 허가해야합니다.");
} else if (hasFineLocationPermission == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "checkPermissions : 퍼미션 가지고 있음");
if ( mGoogleApiClient.isConnected() == false) {
Log.d(TAG, "checkPermissions : 퍼미션 가지고 있음");
mGoogleApiClient.connect();
}
}
}
#Override
public void onRequestPermissionsResult(int permsRequestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
if (permsRequestCode
== PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION && grantResults.length > 0) {
boolean permissionAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (permissionAccepted) {
if ( mGoogleApiClient.isConnected() == false) {
Log.d(TAG, "onRequestPermissionsResult : mGoogleApiClient connect");
mGoogleApiClient.connect();
}
} else {
checkPermissions();
}
}
}
#TargetApi(Build.VERSION_CODES.M)
private void showDialogForPermission(String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
builder.setTitle("알림");
builder.setMessage(msg);
builder.setCancelable(false);
builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ActivityCompat.requestPermissions(mActivity,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
});
builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.create().show();
}
private void showDialogForPermissionSetting(String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
builder.setTitle("알림");
builder.setMessage(msg);
builder.setCancelable(true);
builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
askPermissionOnceAgain = true;
Intent myAppSettings = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + mActivity.getPackageName()));
myAppSettings.addCategory(Intent.CATEGORY_DEFAULT);
myAppSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mActivity.startActivity(myAppSettings);
}
});
builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.create().show();
}
//여기부터는 GPS 활성화를 위한 메소드들
private void showDialogForLocationServiceSetting() {
AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
builder.setTitle("위치 서비스 비활성화");
builder.setMessage("앱을 사용하기 위해서는 위치 서비스가 필요합니다.\n"
+ "위치 설정을 수정하실래요?");
builder.setCancelable(true);
builder.setPositiveButton("설정", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent
= new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(callGPSSettingIntent, GPS_ENABLE_REQUEST_CODE);
}
});
builder.setNegativeButton("취소", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case GPS_ENABLE_REQUEST_CODE:
//사용자가 GPS 활성 시켰는지 검사
if (checkLocationServicesStatus()) {
if (checkLocationServicesStatus()) {
Log.d(TAG, "onActivityResult : 퍼미션 가지고 있음");
if ( mGoogleApiClient.isConnected() == false ) {
Log.d( TAG, "onActivityResult : mGoogleApiClient connect ");
mGoogleApiClient.connect();
}
return;
}
}
break;
}
}
}
and this MainActivity Code
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bttest1 = (Button)findViewById(R.id.bttest1);
bttest1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),Main2Activity.class);
startActivity(intent);
}
});
}
}
Unable to start activity ComponentInfo{...}: java.lang.NullPointerException
An error occurs here.(Main2Activity)
mapFragment.getMapAsync(this);
What is the reason for the error?
Help me, please.
In your Main2Activity onCreate, you use setContentView(R.layout.activity_main);
It seems to be layout from MainActivity, not Main2Activity. You should make something like R.layout.activity_main2 for your second activity.
Then, your code
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
probably won't find view with ID R.id.map, because that view isn't part of first MainActivity layout.
I do not understand the issue
This . when I was still running but socket.emit code app is not running . I try to run it , but it still vs asyn or BroadcastReceiver inactive.
Can I fix this and how to fix ? :
Client.java :
public class MainActivity extends AppCompatActivity {
Button bnt;
LocationManager locationManager;
LocationListener locationListener;
Location location = new Location(LocationManager.GPS_PROVIDER);
public boolean msend = false;
public Socket mSocket;
{
try {
mSocket = IO.socket("http://khanhip.ddns.net:4001");
} catch (URISyntaxException e) {
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mSocket.connect();
mSocket.emit("id",14235);
mSocket.emit("upload","Hello upload");
bnt = (Button) findViewById(R.id.button);
new ui().execute();
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Toast.makeText(MainActivity.this, location.getLatitude() + "", Toast.LENGTH_SHORT).show();
location.set(location);
msend =true;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
Emitter.Listener listener = new Emitter.Listener() {
#Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,args[0].toString(), Toast.LENGTH_SHORT).show();
}
});
}
};
// mSocket.on("log",listener);
config();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 10 : config();
break;
}
}
public void config(){
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}
, 10);
}
return;
}
if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
class ui extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... params) {
while (true) {
while (msend) {
publishProgress();
return null;
}
System.out.println("in");
}
}
#Override
protected void onProgressUpdate(Void... values) {
System.out.println("out");
mSocket.emit("update","HI MOTHER"); // code not work
}
}
}
Server.js
var express = require("express");
var app = express();
var server = require("http").createServer(app);
var io = require("socket.io").listen(server);
server.listen(4000);
var listsocket = [];
var list =[];
var clientid;
var Location = {};
io.sockets.on("connection",function(socket){
socket.on("upload",function (data) {
console.log(data);
});
socket.on("id",function (data) {
console.log(data);
});
});``
I have this code which I use to position a map app. I tested it in a Galaxy S2 device and works fine, but when I tested it in a nexus 4 device the onLocationChanged callback never gets called. What could I be doing wrong?
Here is my activity code:
public class BaseMapActivity extends FragmentActivity implements Injectable,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private MapEntity component;
private boolean yetStarted = false;
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
private Location location;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
mLocationClient = new LocationClient(this, this, this);
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // TODO
mLocationRequest.setInterval(5000); // TODO
mLocationRequest.setFastestInterval(5000); // TODO
replaceFragment(R.id.map_container, mapFragment);
// Agrega el fragment de extras
Fragment extrasFragment = component.getExtrasFragment();
replaceFragment(R.id.map_extras, extrasFragment);
}
#Override
protected void onStart() {
super.onStart();
mLocationClient.connect();
}
#Override
protected void onStop() {
if (mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(this);
mLocationClient.disconnect();
}
super.onStop();
}
#Override
public void onConnected(Bundle arg0) {
mLocationClient.requestLocationUpdates(mLocationRequest, this);
location = mLocationClient.getLastLocation();
if (location == null) {
return;
}
Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
}
#Override
public void onDisconnected() {
mLocationClient.removeLocationUpdates(this);
Toast.makeText(this, "onDisconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
component.setCenter(location);
String msg = "Updated Location: "
+ Double.toString(location.getLatitude()) + ","
+ Double.toString(location.getLongitude());
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST:
switch (resultCode) {
case Activity.RESULT_OK:
break;
}
}
}
#SuppressLint("ShowToast")
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "An error ocurred getting current location",
Toast.LENGTH_SHORT);
}
}
}
Whats weird is that its working in one device but not in the other.
Try to set location mock up to see if the locationChange is called or not.
Here you have an example i was using for this before production.
private Location createMockLocation() {
if (mockLocation == null) {
mockLocation = new Location("mock");
mockLocation.setLatitude(41.4934133);
mockLocation.setLongitude(-23.8729252);
mockLocation.setAccuracy(1.0f);
mockLocation.setTime(new Date().getTime());
} else {
mockLocation.setLatitude(mockLocation.getLatitude() + 0.00003);
mockLocation.setLongitude(mockLocation.getLongitude() + 0.00001);
mockLocation.setTime(new Date().getTime());
}
return mockLocation;
}
private void mockLocation() {
LocationServices.FusedLocationApi.setMockMode(clientApi, true);
LocationServices.FusedLocationApi.setMockLocation(clientApi, createMockLocation());
final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
LocationServices.FusedLocationApi.setMockLocation(clientApi, createMockLocation());
// Log.d("MockLocation",
// "mockLocation: Lat:"+mockLocation.getLatitude()+" Long:"+mockLocation.getLongitude());
}
}, 0, NORMAL_INTERVAL, TimeUnit.MILLISECONDS);
}
With this method you get an update position each NORMAL_INTERVAL in ms.
Hope this helps :).