-1

I am trying to put firebase in my fragment that if someone clicks the checkout button his products should go to the firebase database an there is no error but when I run the app and click the checkout button the app closes down and in the Log cat there is this error.

2021-04-05 06:27:28.000 23477-23477/com.example.naashtae E/xample.naashta: [qarth_debug:]  get PatchStore::createDisableExceptionQarthFile method fail.
2021-04-05 06:27:28.003 23477-23477/com.example.naashtae E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.naashtae, PID: 23477
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.widget.TextView.toString()' on a null object reference
        at com.example.shoppingcart.views.CartFragment.confirm(CartFragment.java:156)
        at com.example.shoppingcart.views.CartFragment$3.onClick(CartFragment.java:132)
        at android.view.View.performClick(View.java:6659)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
        at android.view.View.performClickInternal(View.java:6631)
        at android.view.View.access$3100(View.java:790)
        at android.view.View$PerformClick.run(View.java:26187)
        at android.os.Handler.handleCallback(Handler.java:907)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
2021-04-05 06:27:28.024 23477-23477/com.example.naashtae I/Process: Sending signal. PID: 23477 SIG: 9

CartFragment.java

package com.example.shoppingcart.views;

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



import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;

import com.example.shoppingcart.R;
import com.example.shoppingcart.adapters.CartListAdapter;
import com.example.shoppingcart.cartholder;
import com.example.shoppingcart.databinding.FragmentCartBinding;
import com.example.shoppingcart.dataholder;
import com.example.shoppingcart.models.CartItem;
import com.example.shoppingcart.productholder;
import com.example.shoppingcart.viewmodels.ShopViewModel;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.FirebaseFirestore;

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

public class CartFragment extends Fragment implements CartListAdapter.CartInterface {

    private static final String TAG = "CartFragment";
    private ImageView productImage;
    public TextView productname;
    FirebaseFirestore firebaseFirestore;
    public TextView productprice;
    public Spinner productquantity;
    UUID uuid = UUID.randomUUID();
    String randomUUID = uuid.toString().trim();
    ShopViewModel shopViewModel;
    FragmentCartBinding fragmentCartBinding;
    NavController navController;
    Button button;


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

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {



        // Inflate the layout for this fragment
         fragmentCartBinding = FragmentCartBinding.inflate(inflater, container, false);
        firebaseFirestore = FirebaseFirestore.getInstance();

        return fragmentCartBinding.getRoot();



    }



    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        navController = Navigation.findNavController(view);

        final CartListAdapter cartListAdapter = new CartListAdapter(this);
        fragmentCartBinding.cartRecyclerView.setAdapter(cartListAdapter);
        fragmentCartBinding.cartRecyclerView.addItemDecoration(new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL));

        shopViewModel = new ViewModelProvider(requireActivity()).get(ShopViewModel.class);
        shopViewModel.getCart().observe(getViewLifecycleOwner(), new Observer<List<CartItem>>() {
            @Override
            public void onChanged(List<CartItem> cartItems) {
                cartListAdapter.submitList(cartItems);
                fragmentCartBinding.placeOrderButton.setEnabled(cartItems.size() > 0);
            }
        });

        shopViewModel.getTotalPrice().observe(getViewLifecycleOwner(), new Observer<Double>() {
            @Override
            public void onChanged(Double aDouble) {
                fragmentCartBinding.orderTotalTextView.setText("Total: PKR " + aDouble.toString());


            }
        });

        button = (Button) getView().findViewById(R.id.placeOrderButton);


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                confirm();

            }
        });
    }

    public void confirm() {

        productname =(TextView) getView().findViewById(R.id.productNameTextView);
        productquantity =(Spinner) getView().findViewById(R.id.quantitySpinner);
        productprice =(TextView) getView().findViewById(R.id.priceTextView);

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


        String productName = productname.getText().toString().trim();
        String productQuantity = productquantity.getSelectedItem().toString().trim();
        String productPrice = productprice.toString().trim();
        UUID uuid = UUID.randomUUID();
        String randomUUIDString = uuid.toString().trim();

        cartholder op = new cartholder(productName,productQuantity,productPrice, saveCurrentDate, saveCurrentTime);

        FirebaseDatabase dab = FirebaseDatabase.getInstance();
        DatabaseReference note = dab.getReference(randomUUIDString);

        note.child("Products").setValue(op);


        Intent intent = new Intent(CartFragment.this.getActivity(), CheckoutActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finishActivity();
    }


    @Override
    public void deleteItem(CartItem cartItem) {
        shopViewModel.removeItemFromCart(cartItem);
    }

    @Override
    public void changeQuantity(CartItem cartItem, int quantity) {
        shopViewModel.changeQuantity(cartItem, quantity);
    }



    }

fragment_cart.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="vertical"
        tools:context=".views.CartFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/cartRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            tools:listitem="@layout/cart_row"
            tools:itemCount="2"
            />

        <Space
            android:layout_width="match_parent"
            android:layout_height="16dp" />

        <TextView
            android:id="@+id/orderTotalTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:layout_margin="8dp"
            android:text="Total: PKR 26"
            android:textAppearance="@style/TextAppearance.MaterialComponents.Headline6" />

        <Button
            android:id="@+id/placeOrderButton"
            style="@style/Widget.MaterialComponents.Button.UnelevatedButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:layout_margin="8dp"
            android:text="Proceed To Checkout"
            android:textAppearance="@style/TextAppearance.MaterialComponents.Caption" />
</LinearLayout>
Hacker
  • 1
  • 2
  • Where is your productNameTextView in the .xml? Is not in the fragment? – javdromero Apr 05 '21 at 01:59
  • 1
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Henry Twist Apr 05 '21 at 01:59
  • Is your spelling of the `textView`s as they are spelled in the `xml` file? – Izak Apr 05 '21 at 02:00
  • I think your textviews are in recyclerview items and not in fragment. Hence You have to write this code in the recyclerview Adapter or You can user interface and wrire code in fragment – Bhargav Thanki Apr 05 '21 at 05:06

1 Answers1

0

Make sure you are using same xml file that you have shared above, because the textview id values are not available in shared xml file.

Priyanka
  • 1,791
  • 1
  • 7
  • 12