0

I have some questions of CameraUpdateFactory.

Q1 :

I am trying to do a function that when i click the button it executes function "mapList()"

My "mapList()" is just to change my camera position. // run successfully but not work!!!!

So I use the Google Map API's functions.

My code below -> mapList()

    public void mapList(View view) {
    Intent intentMap = new Intent(this, MapsActivity.class);
    // start map component

    LatLng tagCYCU = new LatLng(24.956867, 121.242846);
    CameraPosition cameraPosition =
            new CameraPosition.Builder()
                    .target(tagCYCU)
                    .zoom(17)   
                    .build();

    CameraUpdateFactory.newLatLng(tagCYCU) ;
    CameraUpdateFactory.newCameraPosition(cameraPosition) ;
    startActivityForResult(intentMap, 0);
    }

Q2 :

In my Maps activity, I want to try to read the informations from other fragments.Because I need it to do something. ( also change camera position )

So I do this code , but always "ERROR" // null object

My code below -> MapsActivity()

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

TextView getTextAddress ;
Spinner getName ;
String addrRestaurant = "", nameRestaurant = "" ;

private GoogleMap mMap;

private GoogleApiClient googleApiClient;

// Location
private LocationRequest locationRequest;

private Location currentLocation;

private Marker currentMarker, itemMarker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(map);
    mapFragment.getMapAsync(this);
}


/**
 * 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;

    // ------------------------------- Get current location ---------------------------------
    LocationManager locationManager = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }

    Location location = locationManager.getLastKnownLocation(locationManager
            .getBestProvider(criteria, false));
    double currentLatitude = location.getLatitude();
    double currentLongitude = location.getLongitude();
    LatLng currentHere = new LatLng(currentLatitude,currentLongitude) ;

    mMap.addMarker(new MarkerOptions().position(currentHere).title("Current Here"));

    // --------------------------------------------------------------------------------------

    // ---------------------------- Tag all restaurants from SQLite--------------------------


    String addrRestaurant = "" ;

    getTextAddress = (TextView)findViewById(R.id.textViewAddress);   
    // what i get , camera change to that position   
    // bur textViewAddress is in other fragments !!

    addrRestaurant = getTextAddress.getText().toString();

    DBHelper dbHelper = new DBHelper(this);
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    String selectQuery =  "SELECT  " +
            Restaurant.KEY_ID    + "," +
            Restaurant.KEY_name  + "," +
            Restaurant.KEY_type  + "," +
            Restaurant.KEY_price + "," +
            Restaurant.KEY_phone + "," +
            Restaurant.KEY_addr  + "," +
            Restaurant.KEY_score +
            " FROM " + Restaurant.TABLE;

    Cursor cursor = db.rawQuery(selectQuery, null);

    int sizeDB = (int) DatabaseUtils.queryNumEntries(db, "Restaurant");
    String infoAddress = "", infoName = "" ;

    for( int indexDB = 0 ; indexDB < sizeDB ; indexDB ++ ) {
        cursor.moveToPosition(indexDB);

        infoName = cursor.getString(cursor.getColumnIndex(Restaurant.KEY_name));
        infoAddress = cursor.getString(cursor.getColumnIndex(Restaurant.KEY_addr)) ;

        Geocoder geoCoder = new Geocoder(this);
        List<Address> addressLocation ;

        try {
            addressLocation = geoCoder.getFromLocationName(infoAddress, 1);
            double latitude = addressLocation.get(0).getLatitude();
            double longitude = addressLocation.get(0).getLongitude();
            LatLng tag = new LatLng(latitude, longitude);
            addMarker(tag, "Foody Restaurants",infoName ); // get mark !
            if(addrRestaurant.equals(infoAddress) == true){     

                // change camera position according to what i get fom other activity

                mMap.moveCamera(CameraUpdateFactory.newLatLng(tag));
                moveMap(tag);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    // --------------------------------------------------------------------------------------
}

private void moveMap(LatLng place) {
    CameraPosition cameraPosition =
            new CameraPosition.Builder()
                    .target(place)
                    .zoom(17)
                    .build();

    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}

private void addMarker(LatLng place, String title, String snippet) {
    BitmapDescriptor icon =
            BitmapDescriptorFactory.fromResource(R.mipmap.ic_tag);

    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(place)
            .title(title)
            .snippet(snippet)
            .icon(icon);

    mMap.addMarker(markerOptions);
}

Locat

Process: com.example.user.foody, PID: 2896 java.lang.NullPointerException:

Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference

at com.example.user.foody.MapsActivity.onMapReady(MapsActivity.java:121)

MapsActivity.java:121 -> ( addrRestaurant = getTextAddress.getText().toString(); )

at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)

I really need help !! Please :( thank you ..

Kevin
  • 155
  • 1
  • 1
  • 9

1 Answers1

1

You can check this sample on GitHub on how to change the camera position for the map. This code snippet runs when the Animate To Sydney button is clicked.

public void onGoToSydney(View view) {
    if (!checkReady()) {
        return;
    }

    changeCamera(CameraUpdateFactory.newCameraPosition(SYDNEY), new CancelableCallback() {
        @Override
        public void onFinish() {
            Toast.makeText(getBaseContext(), "Animation to Sydney complete", Toast.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(getBaseContext(), "Animation to Sydney canceled", Toast.LENGTH_SHORT)
                    .show();
        }
    });
}

Regarding Fragments, check the documentation about adding a Fragment object to the Activity that will handle the map.

Check this SO post on how to fix and what are the possible causes of the NullPointerException.

"The best way to avoid this type of exception is to always check for null when you did not create the object yourself." If the caller passes null, but null is not a valid argument for the method, then it's correct to throw the exception back at the caller because it's the caller's fault.

Community
  • 1
  • 1
abielita
  • 12,126
  • 2
  • 15
  • 52