不在片段中获取活动的上下文

时间:2017-02-05 15:08:56

标签: android android-fragments android-context

我正在开发一个包含购物车管理的电子商务应用程序。现在我有一个片段(CartFragment)和一个连接到recyclerView的适配器(ShowCartAdapter)。

我在一个片段中进行了三次网络呼叫(即1.将项目添加到购物车,2。在购物车中显示项目,3。从购物车中删除项目)。

上面的片段附加到一个活动(ProductDetailActivity)。将项目添加到购物车并在购物车中显示项目是完美的,但第三个即从购物车中删除项目令我不安。我的{{1}中有一个图标删除一个项目,点击我要从 angularPlayer.play(); 删除该项目,现在我从适配器发送一个唯一ID项目到片段但它在cardview上给我空指针我点击那个图标。可能活动不再附加到该片段。下面是我的适配器,片段和活动的代码片段。请帮助我!!!

CartFragment

recyclerview

AdapterShowCart

ProgressDialog(progressDialog=new ProgressDialog(getActivity());)

ProductDetailActivity

public class CartFragment extends Fragment implements RetrofitTaskListener<AddCart> {

    private ProgressDialog progressDialog;
    private RecyclerView recyclerView;
    private AdapterAddCart adapter;
    private AdapterShowCart adapterShowCart;
    private boolean loading = true;
    AddCart addCartList;
    int pageIndex;
    private LinearLayoutManager linearLayoutManager;
    private String  email1,articlCode,image,quantity,cost;
    private static final String STARTING_TEXT = "Four Buttons Bottom Navigation";
    private Button btnCheckout;
    private FragmentTransaction fragmentTransaction;
    private int frag,cartSize;
    private TextView cartEmptyTxt;
    private Context context;
    private SharedPreferences sharedPreference;
    private SharedPreferences.Editor editor;
    private SessionManager session;
    private EditText cmntTxt;


    public CartFragment() {
        // Required empty public constructor
    }

   public static CartFragment newInstance(int text) {
        Bundle args = new Bundle();
        args.putInt(STARTING_TEXT, text);

       CartFragment sampleFragment = new CartFragment();
        sampleFragment.setArguments(args);
        return sampleFragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        articlCode = getArguments().getString("artCode");
        image = getArguments().getString("image");
        quantity = getArguments().getString("quantity");
        cost = getArguments().getString("cost");
        frag = getArguments().getInt("fragment");

        View view =  inflater.inflate(R.layout.fragment_cart, container, false);
        cmntTxt = (EditText)view.findViewById(R.id.comment_txt);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        session = new SessionManager(getActivity().getApplicationContext());

        sharedPreference = getActivity().getSharedPreferences("CART",0);
        editor = sharedPreference.edit();

        ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Cart");

        btnCheckout = (Button)view.findViewById(R.id.btnCheckout);

        cartEmptyTxt = (TextView)view.findViewById(R.id.emptytxt);
        cartEmptyTxt.setVisibility(View.GONE);

        if (!session.isLoggedIn()) {
            cartEmptyTxt.setVisibility(View.VISIBLE);
            btnCheckout.setVisibility(View.GONE);
            cmntTxt.setVisibility(View.GONE);

        }

        btnCheckout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
     FragmentManager fm = getFragmentManager();
                fragmentTransaction = fm.beginTransaction();
                AddressFragment addressFragment = new AddressFragment();
        fragmentTransaction.replace(R.id.fragmentContainer,addressFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();    }
        });
        pageIndex = 0;
        recyclerView = (RecyclerView)view.findViewById(R.id.cart_recycler_view);
         linearLayoutManager=new LinearLayoutManager(getActivity());
   recyclerView.setLayoutManager(linearLayoutManager);
    SQLiteHandler sqLiteHandler = new SQLiteHandler(getActivity());
        List<SessionModel> sessionModelList = sqLiteHandler.getUserDetails();
        Bundle arguments = getArguments();
        if (arguments != null) {
            for (SessionModel sm : sessionModelList){
                email1 = sm.getEmail();
            }

            if (frag == 6){
            callCartService(email1,articlCode,cost,quantity);
            }else if (email1!=null){
                callGetCart(email1);
            }
     }

        return view;
    }
  public void callCartService(String email,String artCode,String price,String qty){
        showProgreass();
        pageIndex = pageIndex + 1;
        String url = String.format(ServerConfigStage.ADD_CART(),email,artCode,price,qty);
        RetrofitTask task = new RetrofitTask<>(CartFragment.this, CommonUtility.HTTP_REQUEST_TYPE.POST, CommonUtility.CallerFunction.ADD_CART_FUNCTION, url,getActivity());
        task.execute();
 }

    public void callGetCart(String email){
        showProgreass();
        pageIndex = pageIndex + 1;
        String url = String.format(ServerConfigStage.GET_CART(),email);
        RetrofitTask task = new RetrofitTask<>(CartFragment.this, CommonUtility.HTTP_REQUEST_TYPE.POST, CommonUtility.CallerFunction.GET_CART, url,getActivity());
        task.execute();
   }

    public void delItemCart(String email,String itemId){
        adapterShowCart = new AdapterShowCart(getContext(),CartFragment.this);
        showProgreass();
        String url = String.format(ServerConfigStage.DEL_ITEM_CART(),email,itemId);
        RetrofitTask task = new RetrofitTask<>(CartFragment.this, CommonUtility.HTTP_REQUEST_TYPE.POST, CommonUtility.CallerFunction.DEL_ITEM_CART, url,getActivity());
        task.execute();
    }
 public void showProgreass(){
        progressDialog=new ProgressDialog(getActivity());
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("Please Wait...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }
    public void stopProgress(){
        if(progressDialog!=null && progressDialog.isShowing())
            progressDialog.cancel();
    }

    @Override
    public void onRetrofitTaskComplete(Response<AddCart> response, Context context, CommonUtility.CallerFunction _callerFunction) {
        stopProgress();
        if (response.isSuccess()) {
            if (response.body() != null) {
            addCartList    =response.body();

              if (_callerFunction == CommonUtility.CallerFunction.ADD_CART_FUNCTION){
                  if (addCartList.getStatus() == 0){
                      cartSize = addCartList.getDeatils().size();
                      editor.putInt("CART_ITEMS",cartSize);
                      editor.commit();
                      Toast.makeText(context, addCartList.getResponse(), Toast.LENGTH_SHORT).show();
                      if (adapter == null) {
                          adapter = new AdapterAddCart(context, R.layout.row_cart, addCartList);
                          recyclerView.setAdapter(adapter);
                      }
                  }else
                    if(addCartList.getStatus()>0) {
                        cartSize = addCartList.getDeatils().size();
                        editor.putInt("CART_ITEMS",cartSize);
                        editor.commit();
          if (adapter == null) {
                        adapter = new AdapterAddCart(context, R.layout.row_cart, addCartList);
                  recyclerView.setAdapter(adapter);

             }

                    adapter.notifyDataSetChanged();
                }else {cartSize = addCartList.getDeatils().size();
                        editor.putInt("CART_ITEMS",cartSize);
                        editor.commit();
                        if (adapter == null) {
                            adapter = new AdapterAddCart(context, R.layout.row_cart, addCartList);

                            recyclerView.setAdapter( adapter );;

                        }

                        adapter.notifyDataSetChanged();


                        Toast.makeText(context, addCartList.getResponse(), Toast.LENGTH_SHORT).show();

                    }
                }else if (_callerFunction == CommonUtility.CallerFunction.GET_CART){
                  if (addCartList.getStatus() == 0){
                      if (addCartList.getCart().size()>0){
                      cartSize = addCartList.getCart().size();
                      editor.putInt("CART_ITEMS",cartSize);
                      editor.commit();
                      }
                  }else
                    if(addCartList.getStatus()>0) {
                        if (addCartList.getCart().size()>0){
                        cartSize = addCartList.getCart().size();
                        editor.putInt("CART_ITEMS",cartSize);
                        editor.commit();}
                        if (adapterShowCart == null) {
                            adapterShowCart = new AdapterShowCart(context, R.layout.row_cart, addCartList);

                            recyclerView.setAdapter(adapterShowCart);
                            ;

                        }
                        adapterShowCart.notifyDataSetChanged();
                }else {
                        cartEmptyTxt.setVisibility(View.VISIBLE);
                    }

                        //Toast.makeText(context, addCartList.getResponse(), Toast.LENGTH_SHORT).show();
                }else if (_callerFunction == CommonUtility.CallerFunction.DEL_ITEM_CART){
                  if (addCartList.getStatus()>0){
                      if (adapterShowCart == null) {
                          adapterShowCart = new AdapterShowCart(context, R.layout.row_cart, addCartList);
                          recyclerView.setAdapter(adapterShowCart);

                      }adapterShowCart.notifyDataSetChanged();

                  }
              }
            }

        }

    }

    @Override
    public void onRetrofitTaskFailure(Throwable t) {
        stopProgress();
       // Toast.makeText(getActivity(),"Fail to load Data",Toast.LENGTH_LONG).show();

        if (getActivity()!= null)
        {
        getActivity().finish();
        }
    }

    public void myFragmentMethod(){
        // make sure to double check casts (to YourActivity) like these before invoking
        ((ProductDetailActivity)getActivity()).myOnResume();
    }


}

栈跟踪

public class AdapterShowCart extends RecyclerView.Adapter<AdapterShowCart.ViewHolder>{
    private AddCart addCartList;
    private RemoveItemCommunication removeItemCommunication;
    private CartFragment cartFragment = new CartFragment();


    Context context;
    private int layoutResourceId,cart;
    private SharedPreferences sharedPreferences;

    public AdapterShowCart(Context context, int layoutResourceId, AddCart addCarts) {
        this.context = context;
        this.layoutResourceId = layoutResourceId;
        this.addCartList = addCarts;
    }

    public AdapterShowCart(Context context, CartFragment cartFragment) {
        this.context = context;
        this.cartFragment=cartFragment;
    }

    public void setOnClickListener(RemoveItemCommunication removeItemCommunication1){
        removeItemCommunication = removeItemCommunication1;
    }

    @Override
    public AdapterShowCart.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_cart, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(AdapterShowCart.ViewHolder viewHolder, int i) {


        viewHolder.tv_android.setText("Price :"+" "+addCartList.getCart().get(i).getPrice());
        viewHolder.tv_art_number.setText("Article No. :"+" "+addCartList.getCart().get(i).getItemCode());
        viewHolder.tvQty.setText("Quantity :"+""+addCartList.getCart().get(i).getCartQuantity());


        //viewHolder.img_android.setImageResource(products.get(i).getAndroid_image_url());
        Picasso.with(context).load(addCartList.getCart().get(i).getURL()).resize(240, 120).into(viewHolder.img_android);
    }

    @Override
    public int getItemCount() {

       // cart = sharedPreferences.getInt("CART_ITEMS",0);


            return addCartList.getCart().size();

    }



    class ViewHolder extends RecyclerView.ViewHolder{
        private TextView tv_android,tv_art_number,tvQty;
        private ImageView img_android,remove;
        private int pos;
        private CardView cardView;
        public ViewHolder(View view) {
            super(view);

            tv_android = (TextView)view.findViewById(R.id.tvTitle);
            tv_art_number=(TextView)view.findViewById(R.id.tvNumber);
            cardView = (CardView)view.findViewById(R.id.card_view);
            img_android = (ImageView) view.findViewById(R.id.mealImage);
            tvQty=(TextView)view.findViewById(R.id.tvQty);
            remove=(ImageView)view.findViewById(R.id.removeItem);
            remove.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int pos = getAdapterPosition();
                    cartFragment.delItemCart(addCartList.getEmail(),addCartList.getCart().get(pos).getId());
                }
            });

            cardView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    pos = getAdapterPosition();



                }
            });
        }
    }

}

2 个答案:

答案 0 :(得分:1)

getActivity返回null的原因是,您正在使用cart片段的实例,该实例已在适配器类中初始化,该类未附加到任何活动。 所以请将CartFragment的一个实例从CartFragment传递给适配器类以解决问题。在AdapterShowCart类中有一个构造函数,其中传递了cart片段实例,但它在片段中的delItemCart(String email,String itemId)中被调用(我不明白为什么这样做)。

答案 1 :(得分:0)

AdapterShowCart第80行中,您正在触发一个操作,该操作尝试使用对不再存在的上下文的引用从资源中获取值。

据推测,ProductDetailActivity.this会导致问题。