Error inflating class fragment, fragment for com.google.android.gms.location.places.ui.PlaceAutocompleteFragment

-1

android.view.InflateException: Binary XML file line #24: Binary XML file line #24: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #24: Error inflating class fragment
Caused by: java.lang.IllegalArgumentException: Binary XML file line #24: Duplicate id 0x7f0901b7, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.location.places.ui.PlaceAutocompleteFragment

This app is a tutorial. I had reviewed the tutorial; over and over without finding a solution to the crash

private void showAlertDialog() {


    AlertDialog.Builder alertDialog = new AlertDialog.Builder(Cart.this);
    alertDialog.setTitle("One more step");
    alertDialog.setMessage("Enter your address:");

    LayoutInflater inflater = this.getLayoutInflater();
    View order_address_comment = inflater.inflate(R.layout.order_address_comment, null);

    //final EditText edtAddress = (EditText)order_address_comment.findViewById(R.id.edtAddress);
    final PlaceAutocompleteFragment edtAddress = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

    edtAddress.getView().findViewById(R.id.place_autocomplete_search_button).setVisibility(View.GONE);
    ((EditText) edtAddress.getView().findViewById(R.id.place_autocomplete_search_input))
            .setHint("Enter your address");
    ((EditText) edtAddress.getView().findViewById(R.id.place_autocomplete_search_input))
            .setTextSize(14);

    edtAddress.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {

            shippingaddress = place;

        }

        @Override
        public void onError(Status status) {

            Log.e("ERROR", status.getStatusMessage());

        }
    });

    final EditText edtComment = (EditText) order_address_comment.findViewById(R.id.edtComment);

    final RadioButton rdiShipToAddress = (RadioButton) order_address_comment.findViewById(R.id.rdiShipToAddress);
    final RadioButton rdiHomeAddress = (RadioButton) order_address_comment.findViewById(R.id.rdiHomeAddress);
    final RadioButton rdiCOD = (RadioButton) order_address_comment.findViewById(R.id.rdiCOD);
    final RadioButton rdiPaypal = (RadioButton) order_address_comment.findViewById(R.id.rdiPayPal);
    final RadioButton rdiBalance = (RadioButton) order_address_comment.findViewById(R.id.rdiEatItBalance);

    rdiHomeAddress.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (b) {
              if (Common.currentUser.getHomeAddress() != null ||
                      !TextUtils.isEmpty(Common.currentUser.getHomeAddress()))
              {
                  address = Common.currentUser.getHomeAddress();
                  ((EditText) edtAddress.getView().findViewById(R.id.place_autocomplete_search_input))
                          .setText(address);
              }

                else 
              {
                  Toast.makeText(Cart.this, "Please update your home address", Toast.LENGTH_SHORT).show();
              }
            }
        }
    });

    rdiShipToAddress.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (b) {
                mGoogleMapService.getAddressName(String.format("https://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",
                        mLastLocation.getLatitude(),
                        mLastLocation.getLongitude()))
                        .enqueue(new Callback<String>() {
                            @Override
                            public void onResponse(Call<String> call, Response<String> response) {

                                try {
                                    JSONObject jsonObject = new JSONObject(response.body().toString());
                                    JSONArray resultsArray = jsonObject.getJSONArray("results");

                                    JSONObject firstObject = resultsArray.getJSONObject(0);

                                    address = firstObject.getString("formatted_address");

                                    ((EditText) edtAddress.getView().findViewById(R.id.place_autocomplete_search_input))
                                            .setText(address);


                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void onFailure(Call<String> call, Throwable t) {
                                Toast.makeText(Cart.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();

                            }
                        });

            }
        }
    });

    alertDialog.setView(order_address_comment);
    alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
    alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {


        @Override
        public void onClick(DialogInterface dialogInterface, int i) {


            if (!rdiShipToAddress.isChecked() && !rdiHomeAddress.isChecked()) {
                if (shippingaddress != null)
                    address = shippingaddress.getAddress().toString();
                else {
                    Toast.makeText(Cart.this, "Please enter address or select address option", Toast.LENGTH_SHORT).show();
                    getFragmentManager().beginTransaction()
                            .remove(getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment))
                            .commit();

                    return;
                }
            }

            if (!TextUtils.isEmpty(address)) {
                Toast.makeText(Cart.this, "Please enter address or select address option", Toast.LENGTH_SHORT).show();
                getFragmentManager().beginTransaction()
                        .remove(getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment))
                        .commit();

                return;

            }
            comment = edtComment.getText().toString();

            if (!rdiCOD.isChecked() && !rdiCOD.isChecked() && !rdiBalance.isChecked()) {
                Toast.makeText(Cart.this, "Please select from payment options", Toast.LENGTH_SHORT).show();
                getFragmentManager().beginTransaction()
                        .remove(getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment))
                        .commit();

                return;

            } else if (rdiPaypal.isChecked()) {

                String formatAmount = txtTotalPrice.getText().toString()
                        .replace("$", "")
                        .replace(",", "");

                PayPalPayment payPalPayment = new PayPalPayment(new BigDecimal(formatAmount),
                        "USD",
                        "Food4Thought App Order",
                        PayPalPayment.PAYMENT_INTENT_SALE);
                Intent intent = new Intent(getApplicationContext(), PaymentActivity.class);
                intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
                intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payPalPayment);
                startActivityForResult(intent, PAYPAL_REQUEST_CODE);

                getFragmentManager().beginTransaction()
                        .remove(getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment))
                        .commit();

            }
            else if
                    (rdiCOD.isChecked())
            {
                Request request = new Request(
                        Common.currentUser.getPhone(),
                        Common.currentUser.getName(),
                        address,
                        txtTotalPrice.getText().toString(),
                        "0",
                        comment,
                        "COD",
                        "Unpaid",
                        String.format("%s,%s",mLastLocation.getLatitude(),mLastLocation.getLongitude()),
                        Common.restaurantSelected,
                        cart
                );

                String order_number = String.valueOf(System.currentTimeMillis());
                requests.child(order_number)
                        .setValue(request);

                new Database(getBaseContext()).cleanCart(Common.currentUser.getPhone());

                sendNotificationOrder(order_number);

                }
                else if (rdiBalance.isChecked())
                {
                    double amount = 0;
                    try {
                        amount = Common.formatCurrency(txtTotalPrice.getText().toString(),Locale.US).doubleValue();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (Common.currentUser.getBalance() >= amount){
                        Request request = new Request(
                                Common.currentUser.getPhone(),
                                Common.currentUser.getName(),
                                address,
                                txtTotalPrice.getText().toString(),
                                "0",
                                comment,
                                "Balance",
                                "Paid",
                                String.format("%s,%s",mLastLocation.getLatitude(),mLastLocation.getLongitude()),
                                Common.restaurantSelected,
                                cart);

                        final String order_number = String.valueOf(System.currentTimeMillis());
                        requests.child(order_number)
                                .setValue(request);

                        new Database(getBaseContext()).cleanCart(Common.currentUser.getPhone());

                       double balance = Common.currentUser.getBalance() - amount;
                        Map<String, Object> update_balance = new HashMap<>();
                        update_balance.put("balance",balance);

                        FirebaseDatabase.getInstance()
                                .getReference("User")
                                .child(Common.currentUser.getPhone())
                                .updateChildren(update_balance)
                                .addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if (task.isSuccessful())
                                        {
                                            FirebaseDatabase.getInstance()
                                                    .getReference("User")
                                                    .child(Common.currentUser.getPhone())
                                                    .addListenerForSingleValueEvent(new ValueEventListener() {
                                                        @Override
                                                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                                            Common.currentUser = dataSnapshot.getValue(User.class);

                                                            sendNotificationOrder(order_number);
                                                        }

                                                        @Override
                                                        public void onCancelled(@NonNull DatabaseError databaseError) {

                                                        }
                                                    });
                                        }

                                    }
                                });

                    }
                    else
                        {
                            Toast.makeText(Cart.this, "Your balance is not enough please choose another payment method", Toast.LENGTH_SHORT).show();
                    }
                }


            getFragmentManager().beginTransaction()
                    .remove(getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment))
                    .commit();
        }


    });
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch(requestCode){
        case LOCATION_REQUEST_CODE:{
            if (grantResults.length >0&& grantResults[0] == PackageManager.PERMISSION_GRANTED){
            }
            if (checkPlayServices())
            {
                buildGoogleApiClient();
                createLocationRequest();
            }

        }
        break;

    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PAYPAL_REQUEST_CODE){


        if (resultCode == RESULT_OK){
            PaymentConfirmation confirmation = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
            if (confirmation != null){
                try {
                    String paymentDetail = confirmation.toJSONObject().toString(4);
                    JSONObject jsonObject = new JSONObject(paymentDetail);


            Request request = new Request(
                    Common.currentUser.getPhone(),
                    Common.currentUser.getName(),
                    address,
                    txtTotalPrice.getText().toString(),
                    "0",
                    comment,
                    "Paypal",
                    jsonObject.getJSONObject("response").getString("state"),
                    String.format("%s,%s",shippingaddress.getLatLng().latitude,shippingaddress.getLatLng().longitude,shippingaddress),
                    Common.restaurantSelected,
                    cart
            );
            String order_number = String.valueOf(System.currentTimeMillis());
            requests.child(order_number)
                    .setValue(request);

            new Database(getBaseContext()).cleanCart(Common.currentUser.getPhone());

            sendNotificationOrder(order_number);

            Toast.makeText(Cart.this,"Thank you for your order",Toast.LENGTH_SHORT).show();
            finish();


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }
        else if (resultCode == Activity.RESULT_CANCELED)
            Toast.makeText(this,"Payment canceled",Toast.LENGTH_SHORT).show();
        else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID)
            Toast.makeText(this,"Invalid payment",Toast.LENGTH_SHORT).show();
    }
}


private void sendNotificationOrder(final String order_number) {
    DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Tokens");
    Query data = tokens.orderByChild("is ServerToken").equalTo(true);
    data.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            for (DataSnapshot postSnapShot:dataSnapshot.getChildren()){
                Token serverToken = postSnapShot.getValue(Token.class);

               // Notification notification = new Notification("Food for Thought","You have new order"+order_number);
               // Sender content = new Sender(serverToken.getToken(),notification);

                Map<String,String>dataSend = new HashMap<>();
                dataSend.put("title","Food for Thought");
                dataSend.put("message","You have a new order" + order_number);
                DataMessage dataMessage = new DataMessage(serverToken.getToken(),dataSend);

                String test = new Gson().toJson(dataMessage);
                Log.d("Content",test);



                mService.sendNotification(dataMessage)
                        .enqueue(new Callback<MyResponse>() {
                            @Override
                            public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {

                                if (response.code()== 200) {
                                    if (response.body().success == 1) {
                                        Toast.makeText(Cart.this, "Thank you for your order", Toast.LENGTH_SHORT).show();
                                        finish();

                                    } else {
                                        Toast.makeText(Cart.this, "Failed", Toast.LENGTH_SHORT).show();

                                    }
                                }


                            }

                            @Override
                            public void onFailure(Call<MyResponse> call, Throwable t) {
                                Log.e("ERROR", t.getMessage());

                            }
                        });
            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}

private void loadListFood() {
    cart = new Database (this).getCarts(Common.currentUser.getPhone());
    adapter = new CartAdapter(cart,this);
    adapter.notifyDataSetChanged();
    recyclerView.setAdapter(adapter);

    int total = 0;
    for (Order order:cart)
        total+=(Integer.parseInt(order.getPrice()))*(Integer.parseInt(order.getQuantity()));
    Locale locale= new Locale("en","US");
    NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
    txtTotalPrice.setText(fmt.format(total));

}

@Override
public boolean onContextItemSelected(MenuItem item) {
    if (item.getTitle().equals(Common.DELETE))
        deleteCart(item.getOrder());
    return true;
}

private void deleteCart(int position) {
    cart.remove(position);
    new Database(this).cleanCart(Common.currentUser.getPhone());
    for (Order item : cart)
        new Database(this).addToCart(item);

    loadListFood();
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    displayLocation();
    startLocationUpdates();

}

private void startLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);
}

private void displayLocation() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        return;
    }
   mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mLastLocation != null){
        Log.d("LOCATION", "Your location : "+mLastLocation.getLatitude()+ ","+mLastLocation.getLongitude());
    }
    else {
        Log.d("LOCATION", "Could not get your location");
    }
}

@Override
public void onConnectionSuspended(int i) {
    mGoogleApiClient.connect();

}

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

}

@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    displayLocation();

}
android
google-maps
fragment
asked on Stack Overflow May 21, 2019 by SAmendariz • edited May 21, 2019 by geocodezip

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0