无法填充重复的片段(com.google.android.gms.location.places.ui.PlaceAutocompleteFragment)

时间:2019-05-22 23:53:23

标签: android android-dialogfragment google-api-client

错误夸大类片段重复ID 0x7f0901b7,标记null或父ID 0xffffffff与com.google.android.gms.location.places.ui.PlaceAutocompleteFragment的另一个片段

这是我一直在努力的教程。我看不到找到解决办法

public class Cart extends AppCompatActivity implements 
GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
LocationListener,RecyclerItemTouchHelperListener {

private static final int PAYPAL_REQUEST_CODE = 9999;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;

FirebaseDatabase database;
DatabaseReference requests;

public TextView txtTotalPrice;
Button btnPlace;
List<Order> cart = new ArrayList<>();
CartAdapter adapter;

APIService mService;

RelativeLayout rootLayout;

Place shippingaddress;

static  PayPalConfiguration config = new PayPalConfiguration()
        .environment(PayPalConfiguration.ENVIRONMENT_SANDBOX)
        .clientId(Config.PAYPAL_CLIENT_ID);

String address,comment;

private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private static final int UPDATE_INTERVAL = 5000;
private static final int FASTEST_INTERVAL = 3000;
private static final int DISPLACEMENT = 10;
private static final int LOCATION_REQUEST_CODE = 9999;
private static final int PLAY_SERVICES_REQUEST = 9997;

IGoogleService mGoogleMapService;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cart);

    mGoogleMapService = Common.getGoogleMapAPI();

    rootLayout = (RelativeLayout)findViewById(R.id.rootLayout);

    if (ActivityCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_COARSE_LOCATION) != 
PackageManager.PERMISSION_GRANTED)
    {
        ActivityCompat.requestPermissions(this,new String[]
                {
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION

                }, LOCATION_REQUEST_CODE);
    }
    else {
        if (checkPlayServices())
        {
            buildGoogleApiClient();
            createLocationRequest();
        }
    }

    Intent intent = new Intent(this, PayPalService.class);
    intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION,config);
    startService(intent);

    mService = Common.getFCMService();

    database = FirebaseDatabase.getInstance();
    requests = database.getReference("Restaurants").
 child(Common.restaurantSelected).child("Requests");

    recyclerView = (RecyclerView)findViewById(R.id.listCart);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);

    ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new 
  RecyclerItemTouchHelper(0,ItemTouchHelper.LEFT, this);
    new  
 ItemTouchHelper(itemTouchHelperCallback)
.attachToRecyclerView(recyclerView);

    txtTotalPrice = (TextView)findViewById(R.id.total);
    btnPlace = (Button)findViewById(R.id.btnPlaceOrder);

    btnPlace.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showAlertDialog();

            }
    });
    if (cart.size() > 0)
        showAlertDialog();
    else
        Toast.makeText(Cart.this,"Your cart is empty", 
Toast.LENGTH_SHORT).show();

    loadListFood();

}

 private void createLocationRequest() {
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setSmallestDisplacement(DISPLACEMENT);

    }

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

    mGoogleApiClient.connect();
 }

private boolean checkPlayServices() {
    int resultCode = 
GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS){
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
            GooglePlayServicesUtil.
getErrorDialog(resultCode,this,PLAY_SERVICES_REQUEST).show();

        else {
            Toast.makeText(this,"This device does not support location 
services",Toast.LENGTH_SHORT).show();
            finish();
        }
        return false;
    }
    return true;

}

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

}


@Override
public void onSwipe(RecyclerView.ViewHolder viewHolder, int direction, int 
position) {
    if (viewHolder instanceof CartViewHolder){
        String name = ((CartAdapter)recyclerView.getAdapter())
.getItem(viewHolder.getAdapterPosition()).getProductName();

        final Order deleteItem = 
((CartAdapter)recyclerView.getAdapter())
.getItem(viewHolder.getAdapterPosition());
        final int deleteIndex = viewHolder.getAdapterPosition();

        adapter.removeItem(deleteIndex);
       new 
Database(getBaseContext()).removeFromCart(deleteItem.getProductId()
,Common.currentUser.getPhone());

        int total = 0;
        List<Order> orders = new 
Database(getBaseContext()).getCarts(Common.currentUser.getPhone());
        for (Order item : orders)
            total += (Integer.parseInt(item.getPrice())) * 
(Integer.parseInt(item.getQuantity()));
        Locale locale = new Locale("en", "US");
        NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
        txtTotalPrice.setText(fmt.format(total));

        Snackbar snackbar = Snackbar.make(rootLayout, name + "removed from 
cart",Snackbar.LENGTH_LONG);
        snackbar.setAction("UNDO", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter.restoreItem(deleteItem,deleteIndex);
                new Database(getBaseContext()).addToCart(deleteItem);

                int total = 0;
                List<Order> orders = new 
Database(getBaseContext()).getCarts(Common.currentUser.getPhone());
                for (Order item : orders)
                    total += (Integer.parseInt(item.getPrice())) * 
(Integer.parseInt(item.getQuantity()));
                Locale locale = new Locale("en", "US");
                NumberFormat fmt = 
NumberFormat.getCurrencyInstance(locale);
                txtTotalPrice.setText(fmt.format(total));

            }
        });
        snackbar.setActionTextColor(Color.RED);
        snackbar.show();


    }

}
}

logcat 原因:android.view.InflateException:二进制XML文件行#24:错误夸大类片段     造成原因:java.lang.IllegalArgumentException:二进制XML文件第24行:重复的ID 0x7f0901b7,标记为null或父ID 0xffffffff与com.google.android.gms.location.places.ui.PlaceAutocompleteFragment

的另一个片段重复

0 个答案:

没有答案