mapview and cameraupdate in api v2 - android-mapview

Why the CameraUpdateFactory class is not working in my project?
The app crashes if it executes the following command:
CameraUpdate pino= CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
If i remove that line (and of course the next one), the code successfully starts and shows the map.
I need the mapView and i need to use the new api v2.
I declare the mapView in layout in this way:
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/mappa"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/buttonBar"
map:uiZoomControls="false"
/>
then in mainActivity.java i wrote this:
public class MainActivity extends FragmentActivity implements LocationListener, LocationSource {
public static boolean locatingMe=true;
public GoogleMap mappa;
public MapView mapView;
private OnLocationChangedListener onLocationChangedListener;
private LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mappa);
mapView.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//You may want to pass a different provider in as the first arg here
//depending on the location accuracy that you desire
//see LocationManager.getBestProvider()
Criteria locationCriteria = new Criteria();
locationCriteria.setAccuracy(Criteria.NO_REQUIREMENT);
locationManager.requestLocationUpdates(locationManager.getBestProvider(locationCriteria, true), 1L, 2F, this);
if (mappa == null) {
mappa=mapView.getMap();
//This is how you register the LocationSource
mappa.setLocationSource(this);
mappa.getUiSettings().setMyLocationButtonEnabled(false);
mappa.setMyLocationEnabled(true);
}
}
#Override
public void onPause()
{
if(locationManager != null)
{
locationManager.removeUpdates(this);
}
mapView.onPause();
super.onPause();
}
#Override
public void onResume()
{
checkGooglePlayServicesAvailability();
checkGps();
mapView.onResume();
super.onResume();
}
#Override
protected void onDestroy() {
mapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void activate(OnLocationChangedListener listener)
{
onLocationChangedListener = listener;
}
#Override
public void deactivate()
{
onLocationChangedListener = null;
}
#Override
public void onLocationChanged(Location location)
{
if( onLocationChangedListener != null )
{
onLocationChangedListener.onLocationChanged( location );
//Move the camera to the user's location once it's available!
//only if locatingMe is true
if (locatingMe) {
if (mappa!=null){
CameraUpdate pino= CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
mappa.animateCamera(pino);
}
}
}
}
#Override
public void onProviderDisabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(this, "provider disabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(this, "provider enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO Auto-generated method stub
Toast.makeText(this, "status changed", Toast.LENGTH_SHORT).show();
}
The error in the LogCat is the following:
Caused by: java.lang.NullPointerException: CameraUpdateFactory is not initialized.

I solved the problem by adding on the "onCreate" the following lines:
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
the reason is that the CameraUpdateFactory needs to be initilized (even if from documentation it seems that using mapview it shoud be automatically initialized)
I even replaced "public class MainActivity extends FragmentActivity" with "public class MainActivity extends Activity". But i think that this last thing it was not needed..

if i use:
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
The exception give me this error:
Unreachable catch block for GooglePlayServicesNotAvailableException.
This exception is never thrown from the try statement body".
I have use only:
MapsInitializer.initialize(this);
:)

Related

Step Counter in Android Studio doesn't count steps

I have a problem with an app I'm trying to develop in Android Studio. I'm trying to develop a step counter using the STEP_COUNTER sensor in a Fragment.I decided to show my results in a TextView ('mStepsSinceReboot'), but it keeps being empty. Do you have any idea on how to make it work?
An hypotesis is that I should use a Service, but online I only found implementations that don't require it.
Thanks in advance for your answer. This is the code of my Fragment.
public class StepFragment extends Fragment implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mStepCounter;
private boolean isSensorPresent;
private TextView mStepsSinceReboot;
public StepFragment() {
// Required empty public constructor
}
public static StepFragment newInstance(String param1, String param2) {
StepFragment fragment = new StepFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v=inflater.inflate(R.layout.fragment_step, container, false);
mStepsSinceReboot=v.findViewById(R.id.stepssincereboot);
mSensorManager=(SensorManager) this.getActivity().getSystemService(getContext().SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)!=null){
mStepCounter=mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
isSensorPresent=true;
}
else{
isSensorPresent=false;
}
return v;
}
#Override
public void onSensorChanged(SensorEvent event) {
mStepsSinceReboot.setText(("Steps since reboot: "+String.valueOf(event.values[0])));
Log.d("Passi", String.valueOf(mStepsSinceReboot));
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onResume(){
super.onResume();
if(isSensorPresent){
mSensorManager.registerListener(this,mStepCounter,SensorManager.SENSOR_DELAY_NORMAL);
}
}
#Override
public void onPause(){
super.onPause();
if(isSensorPresent){
mSensorManager.unregisterListener(this);
}
}
#Override
public void onDestroy(){
super.onDestroy();
mSensorManager=null;
mStepCounter=null;
}
}
you added the permission in the manifest file ?
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>

How to start service in main activity by coding proximity sensor in service class

How to start service in main activity by coding proximity sensor in the service class.
my code not working please tell me
This Service class
public class ModeOnOff extends Service {
private SensorManager sensorManager;
private Sensor proximitySensor;
private SensorEventListener proximitySensorListener;
#Override
public void onCreate() {
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
if (sensorManager!=null){
Sensor proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
if (proximitySensor!=null) {
sensorManager.registerListener(proximitySensorListener, proximitySensor, SensorManager.SENSOR_DELAY_NORMAL);
}
} else {
Toast.makeText(this, "Senor service not detected.", Toast.LENGTH_SHORT).show();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Sensor();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
//Function
private void Sensor(){
proximitySensorListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType()==Sensor.TYPE_PROXIMITY){
if (sensorEvent.values[0] > 3){
Toast.makeText(ModeOnOff.this, "Hii", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ModeOnOff.this, "By", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
}
}
And This Main Activity
public class MainActivity extends AppCompatActivity {
Button btnSensor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSensor = findViewById(R.id.btnSensor);
btnSensor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(MainActivity.this, ModeOnOff.class));
}
});
}
}
I want to code the proximity sensor in the service class and start the service from the main activity
how to startService - startService(new Intent(MainActivity.this, ModeOnOff.class));

How autocall method in JavaFX?

I have scene with label which shows what part of hardware are being checked at the moment, so i need invoke "checkMethod" automatically after scene has been drawn, how can i do it in JavaFX?
Here is how to do something when the Scene is shown:
stage.setOnShown(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent arg0) {
// TODO Auto-generated method stub
checkMethod();
}
});
You also have this other methods: setOnCloseRequest, setOnHidden, setOnHiding, setOnShowing.
The option proposed in comments Its the followin:
scene.windowProperty().addListener(new ChangeListener<Window>() {
#Override
public void changed(ObservableValue<? extends Window> arg0,
Window oldVal, Window newVal) {
if(oldVal != null){
oldVal.setOnShown(null);
}
if(newVal != null){
newVal.setOnShown(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent arg0) {
// TODO Auto-generated method stub
checkMethod();
}
});
}
}
});

How to open dialog box in android as soon as game ends from surfaceview class

I have made a SurfaceView subclass in MainActivity which runs some animation/game/thread via canvas draw and I want a dialog box to appear as soon as game ends. I have made a function called openNewGameDialog where I call new AlertDialog.Builder(MainActivity.this) however since I am calling this from a thread it gives error. Please help!! Following is the code:
public class MainActivity extends Activity implements OnTouchListener{
GameSurface dSurface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dSurface=new GameSurface(this);
dSurface.setOnTouchListener(this);
initialize();
setContentView(dSurface);
}
private void initialize(){
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
dSurface.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
dSurface.resume();
}
private void openNewGameDialog(){
new AlertDialog.Builder(MainActivity.this)
.setTitle("hhhhhh")
.setItems(R.array.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
})
.show();
}
public class GameSurface extends SurfaceView implements Runnable{
SurfaceHolder gameHolder;
Thread gameThread = null;
public GameSurface(Context context) {
super(context);
// TODO Auto-generated constructor stub
gameHolder = getHolder();
}
public void pause(){
isRunning = false;
while(true)
{
try {
gameThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
gameThread=null;
}
public void resume(){
isRunning = true;
gameThread = new Thread(this);
gameThread.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
while(isRunning){
if(!gameHolder.getSurface().isValid())
continue;
Canvas canvas = gameHolder.lockCanvas();
canvas.draw something
if game==ends
openNewGameDialog();
gameHolder.unlockCanvasAndPost(canvas);
}
}
}
}
You must put the contents of openNewGameDialog() in a Runnable instead of a method and then call the runOnUiThread(Runnable r) method of the Activity class using that Runnable.
Any kind of UI manipulation can only be done by the UI thread. TherunOnUiThread(Runnable r) method queues the Runnable to the UI thread event queue.

ActionBar tabs with MapView

I've created app using SherlockActionBar tab. One with my tabs contains MapView (Google Maps v2). Currently I have problem when I change tabs (screen below):
enter link description here
Next tab should contain ListView. Sometimes context second tab loaded correctly. Also I have problem with swiping my MapView. Currently I can only swiping up and down direction. I hope that somebody help me.
My code:
myfragment.xml
<com.google.android.gms.maps.MapView
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true" />
TabFragment_Map.java
public class TabFragment_Map extends SherlockFragment {
MapView mapView;
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.map_fragment, container, false);
mapView = (MapView) view.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
return view;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
mapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
mapView.onLowMemory();
super.onLowMemory();
}
}
MainActivity.java
public class MainActivity extends SherlockFragmentActivity {
ViewPager mViewPager;
TabsAdapter mTabsAdapter;
String TabFragment_Cafes;
String TabFragment_Details;
//Settery & gettery używane w mechanizmie przesyłania informacji pomiędzy fragmentami
public String getTabFragment_Cafes() {
return TabFragment_Cafes;
}
public void setTabFragment_Cafes(String tabFragment_Cafes) {
TabFragment_Cafes = tabFragment_Cafes;
}
public String getTabFragment_Details() {
return TabFragment_Details;
}
public void setTabFragment_Details(String tabFragment_Details) {
TabFragment_Details = tabFragment_Details;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.DISPLAY_SHOW_HOME);
bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText("Mapa"), TabFragment_Map.class, null);
mTabsAdapter.addTab(bar.newTab().setText("Kawiarnie"), TabFragment_Cafes.class, null);
mTabsAdapter.addTab(bar.newTab().setText("Szczegóły"), TabFragment_Details.class, null);
if (savedInstanceState != null)
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
//super.onSaveInstanceState(outState);
outState.putInt("tab", getSupportActionBar().getSelectedNavigationIndex());
}
public static class TabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(FragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = ((SherlockFragmentActivity)activity).getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
public void onPageScrollStateChanged(int arg0) {}
public void onPageScrolled(int arg0, float arg1, int arg2) {}
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i = 0; i < mTabs.size(); i++) {
if (mTabs.get(i) == tag)
mViewPager.setCurrentItem(i);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
public void onTabReselected(Tab tab, FragmentTransaction ft) {}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
#Override
public int getCount() {
return mTabs.size();
}
}
}
You need a custom viewpager that intercepts the swipes
package com.ecs.google.maps.v2.component;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
public class CustomViewPager extends ViewPager {
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
// When using Maps V1
// if(v instanceof MapView){
// return true;
// }
// return super.canScroll(v, checkV, dx, x, y);
// When using Maps V2
if (v.getClass().getPackage().getName().startsWith("maps.")) {
return true;
}
return super.canScroll(v, checkV, dx, x, y);
}
}
Put this in your layout :
<com.ecs.google.maps.v2.component.CustomViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabs"
tools:context=".MainActivity">
And the swiping gestures should work.

Resources