'Change ImageView after choosing photo from Gallery

I am trying to change my imageview when its on click and then choose image from gallery then change it. But I don't think its working since when I tried running my project, it just crashes out of the app.

Navigation Drawer

enter image description here

ActivityResult

ActivityResultLauncher<String> mGetContent = registerForActivityResult(
        new ActivityResultContracts.GetContent(),
        new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri uri) {
                // Handle the returned Uri
            }
        });

ImageView

    profileImage = (ImageView) findViewById(R.id.profilepic);

    profileImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mGetContent.launch("image/*");
        }
    });

p.s. The ImageView is inside my navigation drawer. what I wanted to do is that whenever I click or press the ImageView which is the Hamburger Icon, it will redirect to gallery to choose image and then change it once the user chose one.

MapsActivity.java

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{

private static final String TAG = "";
private DrawerLayout drawer;
LatLng carWash1 = new LatLng(6.106535, 125.187230);
LatLng carWash2 = new LatLng(6.106123, 125.189280);

private ArrayList<LatLng> locationArrayList;

private ImageView profileImage;
final static int Gallery_Pick = 1;
private GoogleMap mMap;
private ActivityMapsBinding binding;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location recentLocation;
private Marker currentMark;
private static final int Request_User_Location = 1234;

private List<Polyline> polylines = null;

protected LatLng start = null;
protected LatLng end = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = ActivityMapsBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkUserLocationPermission();
    }

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

    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    drawer = findViewById(R.id.drawer_layout);

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    locationArrayList = new ArrayList<>();

    locationArrayList.add(carWash1);
    locationArrayList.add(carWash2);
}

@Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
    super.onBackPressed();
}


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


public boolean checkUserLocationPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location);
        }
        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case Request_User_Location:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    if (googleApiClient == null) {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }
            } else {
                Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
            }
            return;
    }
}



@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }

    for (int i = 0; i < locationArrayList.size(); i++) {
        mMap.addMarker(new MarkerOptions().position(locationArrayList.get(0)).title("Purok 5 Carwashan").icon(BitMapFromVector(getApplication(), R.drawable.ic_baseline_airplanemode_active_24)));
        mMap.addMarker(new MarkerOptions().position(locationArrayList.get(1)).title("Stratford Carwashan").icon(BitMapFromVector(getApplication(), R.drawable.ic_baseline_airplanemode_active_24)));

        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(locationArrayList.get(i), 15));

        mMap.moveCamera(CameraUpdateFactory.newLatLng(locationArrayList.get(i)));
    }

    boolean success = googleMap.setMapStyle(new MapStyleOptions(getResources()
            .getString(R.string.style_json)));

    if (!success) {
        Log.e(TAG, "Style parsing failed.");
    }
}

private BitmapDescriptor BitMapFromVector(Context context, int vectorResId) {
    // below line is use to generate a drawable.
    Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId);

    // below line is use to set bounds to our vector drawable.
    vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());

    // below line is use to create a bitmap for our
    // drawable which we have added.
    Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);

    // below line is use to add bitmap in our canvas.
    Canvas canvas = new Canvas(bitmap);

    // below line is use to draw our
    // vector drawable in canvas.
    vectorDrawable.draw(canvas);

    // after generating our bitmap we are returning our bitmap.
    return BitmapDescriptorFactory.fromBitmap(bitmap);
}

protected synchronized void buildGoogleApiClient() {
    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    googleApiClient.connect();
}

@Override
public void onLocationChanged(@NonNull Location location) {
    recentLocation = location;

    if (currentMark != null) {
        currentMark.remove();
    }

    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Location!");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

    currentMark = mMap.addMarker(markerOptions);

    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomBy(12));

    if (googleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
    }
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    locationRequest = new LocationRequest();
    locationRequest.setInterval(1100);
    locationRequest.setFastestInterval(1100);
    locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    }

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

}



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source