如何在 Android Studio 中的 Activity 中使用 requireActivity()

How to use requireActivity() in an Activity in Android Studio

我正在尝试 android 申请。但是 requireActivity() 给出了这个错误

Cannot resolve method 'requireActivity' in 'ProductDetailActivity'

但是如果我把它放在片段中,它不会出错。我正在尝试将用户添加到购物车的东西放到 firebase 实时数据库中。请帮助我,我是 Android 的新手。我的代码:

产品DetailsActivity.java

package com.example.shoppingcart.views;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.shoppingcart.R;
import com.example.shoppingcart.adapters.ShopListAdapter;
import com.example.shoppingcart.databinding.FragmentProductDetailBinding;
import com.example.shoppingcart.viewmodels.ShopViewModel;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.UUID;

public class ProductDetailActivity extends AppCompatActivity {
    FragmentProductDetailBinding fragmentProductDetailBinding;
    ShopViewModel shopViewModel;
    private Button addToCartButton;
    private ImageView productImage;
    private TextView productname,productprice,productcategory;
    private String productID="";
    UUID uuid = UUID.randomUUID();
    String randomUUIDString = uuid.toString().trim();
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);
        productID=getIntent().getStringExtra("pid");

        addToCartButton=(Button) findViewById(R.id.addToCartButton);
        productImage=(ImageView) findViewById(R.id.productImageView);
        productname=(TextView) findViewById(R.id.productNameTextView);
        productprice=(TextView) findViewById(R.id.productTotalPriceTextView);
        productcategory=(TextView) findViewById(R.id.Category);



        addToCartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addingToCartList();
            }
        });
    }

    
    private void addingToCartList() {
        String saveCurrentDate,saveCurrentTime;

        Calendar calForDate = Calendar.getInstance();
        SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
        saveCurrentDate = currentDate.format(calForDate.getTime());

        SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a");
        saveCurrentTime = currentTime.format(calForDate.getTime());

        final DatabaseReference cartListRef= FirebaseDatabase.getInstance().getReference().child("Cart List");

        final HashMap<String, Object> cartMap=new HashMap<>();
        cartMap.put("pid",productID);
        cartMap.put("pname",productname.getText().toString());
        cartMap.put("pprice",productprice.getText().toString());
        cartMap.put("pcategory",productcategory.getText().toString());
        cartMap.put("time",saveCurrentTime);
        cartMap.put("date",saveCurrentDate);

        cartListRef.child("User View").child(randomUUIDString)
                .child("Products").child(productID)
                .updateChildren(cartMap)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if(task.isSuccessful()) {
                            cartListRef.child("Admin View").child(randomUUIDString)
                                    .child("Products").child(productID)
                                    .updateChildren(cartMap)
                                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {
                                            if(task.isSuccessful()) {
                                                Toast.makeText(ProductDetailActivity.this,"Added to Cart",Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                        }
                    }
                });
    }



    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {


        shopViewModel = new ViewModelProvider(requireActivity()).get(ShopViewModel.class);
        fragmentProductDetailBinding.setShopViewModel(shopViewModel);
    }

}

requireActivity()是Fragment的一种方法。如果在 Activity 中需要 Activity 对象,只需使用 this:

shopViewModel = new ViewModelProvider(this).get(ShopViewModel.class);