我有一个MainActivity,其中包含带有BottomSheetDialog的HomeFragment。 BottomSheetDialog具有一个EditText,该文本具有一个OnClickListener,用于使用“位置”在GoogleMap中搜索位置。但是,当我单击EditText时,startActivityForResult()行会发生错误。
这是MainActivity.java:-
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
Toolbar toolbar;
Session session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new Session(this);
toolbar = findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
toolbar.setTitle("Driver");
drawerLayout = findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, new HomeFragment(), "Home").commit();
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.home){
HomeFragment homeFragment = new HomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, homeFragment, "Home");
fragmentTransaction.commit();
} else if (id == R.id.sign_out){
session.clearSessions();
startActivity(new Intent(this,LoginActivity.class));
finish();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
这是HomeFragment.java:-
public class HomeFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private static final int REQUEST_LOCATION_PERMISSION = 0;
private static final int REQUEST_LOCATION = 199;
private Button user_action;
private TextView header;
private GoogleMap mMap;
private boolean isDriver;
private int latitude, longitude;
GoogleApiClient googleApiClient;
Location mLastLocation;
FusedLocationProviderClient mFusedLocationClient;
LocationRequest locationRequest;
PendingResult<LocationSettingsResult> result;
EditText txtDestination, txtDepartureTime, txtCapacity;
Button btnSubmitDetails;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_home, container, false);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
user_action = rootView.findViewById(R.id.user_action);
Button btn_driver = rootView.findViewById(R.id.btn_driver);
Button btn_passenger = rootView.findViewById(R.id.btn_passenger);
final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(rootView.getContext());
bottomSheetDialog.setContentView(R.layout.bottom_sheet);
bottomSheetDialog.setCanceledOnTouchOutside(true);
txtDestination = bottomSheetDialog.findViewById(R.id.destination);
txtDepartureTime = bottomSheetDialog.findViewById(R.id.departure_time);
txtCapacity = bottomSheetDialog.findViewById(R.id.capacity);
btnSubmitDetails = bottomSheetDialog.findViewById(R.id.btn_ride_details);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(Objects.requireNonNull(getContext()));
googleApiClient = new GoogleApiClient.Builder(getContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
googleApiClient.connect();
Places.initialize(getContext(),getResources().getString(R.string.google_maps_key));
btn_driver.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
user_action.setText(getString(R.string.offer_ride));
userStatus(true);
Toast.makeText(getContext(),"You are now a driver",Toast.LENGTH_SHORT).show();
}
});
btn_passenger.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
user_action.setText(getString(R.string.find_ride));
userStatus(false);
Toast.makeText(getContext(),"You are now a passenger",Toast.LENGTH_SHORT).show();
}
});
user_action.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, new FindDestinationFragment(), "Home");
fragmentTransaction.commit();*/
{
txtDestination.setFocusable(false);
txtDestination.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<Place.Field> fieldList = Arrays.asList(Place.Field.ADDRESS
, Place.Field.LAT_LNG, Place.Field.NAME);
Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, fieldList).build(rootView.getContext());
startActivityForResult(intent, 100);
}
});
if (txtDestination.getText().toString().isEmpty()) {
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout, new FindDestinationFragment(), "Home");
fragmentTransaction.commit();
}
btnSubmitDetails.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String destination = txtDestination.getText().toString();
String time = txtDepartureTime.getText().toString();
String capacity = txtCapacity.getText().toString();
if (destination.isEmpty() && time.isEmpty() && capacity.isEmpty()) {
Toast.makeText(getContext(), "Some fields are empty", Toast.LENGTH_SHORT).show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(rootView.getContext());
builder.setTitle("Ride Information");
builder.setMessage("Destination:\t\t" + destination + "\nDeparture time:\t\t" + time + "\nCapacity:\t\t" + capacity);
builder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
bottomSheetDialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
});
bottomSheetDialog.show();
}
}
});
return rootView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
Log.d("onActivityResult()",Integer.toString(resultCode));
if (requestCode == REQUEST_LOCATION) {
if (resultCode == Activity.RESULT_OK) {
enableMyLocation();
}
}
if (requestCode == 100 && resultCode == Activity.RESULT_OK){
Place place = Autocomplete.getPlaceFromIntent(data);
txtDestination.setText(place.getName());
} else if (resultCode == AutocompleteActivity.RESULT_ERROR){
Status status = Autocomplete.getStatusFromIntent(data);
Toast.makeText(getContext(), status.getStatusMessage(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30*1000);
locationRequest.setFastestInterval(5*1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient,builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()){
case LocationSettingsStatusCodes.SUCCESS:
enableMyLocation();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(getActivity(),REQUEST_LOCATION);
} catch (IntentSender.SendIntentException e){
e.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
enableMyLocation();
}
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
mLastLocation = location;
LatLng pos = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(pos).title("Current Location"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 15));
} else {
enableMyLocation();
}
}
});
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION);
}
}
@Override
public void onStop() {
super.onStop();
}
private void userStatus(boolean status){
this.isDriver = status;
}
}
捕获的错误表明该片段未附加到活动。我想使用“地方”类搜索地方,并获取选定的地方,并将其返回以显示在TextView txtDestination
中。对于如何解决此错误的任何帮助,将不胜感激。