Click here to Skip to main content
15,937,012 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.append(java.lang.CharSequence)' on a null object reference


Cart.java
Java
<pre>
public class Cart extends AppCompatActivity {

    TextView textViewCartData;
    TextView itemWeight;
    TextView itemPrice;
    TextView textViewDisDur;
    SharedPreferences sharedPreferences;
    Button buttonConfirm;
    ImageView buttonRemove;

    RecyclerView recyclerView;
    ArrayList<ListData> arrayList;

    int pricePerKM = 5;
    String urlConfirm =
            "link/confirm?user_email=";

    String urlRemove =
            "link/cart/clear?user_email=";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);
        recyclerView = findViewById(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(linearLayoutManager);


        textViewDisDur = findViewById(R.id.textDisDur);
        sharedPreferences = getSharedPreferences("CustomerApp", MODE_PRIVATE);
        buttonConfirm = findViewById(R.id.btnConfirmOrder);
        buttonRemove = findViewById(R.id.btnClearCart);
        fetchData();
        buttonConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                sendRequest(view, urlConfirm + sharedPreferences.getString("email", ""));
            }
        });

        buttonRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendRequest(view, urlRemove + sharedPreferences.getString("email", ""));
            }
        });
    }

    public void sendRequest(View v, String apiUrl) {
        Log.e("url", apiUrl);
        v.setEnabled(false);
        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        StringRequest stringRequest = new StringRequest(Request.Method.GET, apiUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                v.setEnabled(true);
                if (response.equals("success")) {
                    Toast.makeText(getApplicationContext(), "Operation success", Toast.LENGTH_SHORT).show();
                    finish();
                } else
                    Toast.makeText(getApplicationContext(), "Operation failed", Toast.LENGTH_SHORT).show();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                v.setEnabled(true);
                error.printStackTrace();
            }
        });
        queue.add(stringRequest);
    }

    public void parseJSON(String data) {
        try {
            JSONArray jsonArray = new JSONArray(data);
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            JSONArray jsonArray1 = jsonObject.getJSONArray("cart");
            for (int i = 0; i < jsonArray1.length(); i++) {
                JSONObject stu = jsonArray1.getJSONObject(i);
                String id = stu.getString("id");
                String name = stu.getString("name");
                String des = stu.getString("description");
                String numItem = stu.getString("numItem");
                String price = stu.getString("price");
                textViewCartData.append("Item: " + name + "");
                itemWeight.append("Ceki: " + numItem + "");
                itemPrice.append("" + price + "");
            }
            String distance = String.valueOf(jsonObject.getInt("distance") / 1000);
            String duration = String.valueOf((jsonObject.getInt("duration") / 60));
            int total_price = Integer.parseInt(distance) * pricePerKM;
            textViewDisDur.setText("Distance: " + distance + " KM\nDelivery Fee: "
                    + total_price + " $" + "\nDuration: " + duration + "Minutes");
        } catch (JSONException e) {
            Log.e("error", e.getLocalizedMessage());
            e.printStackTrace();
        }
        CartListAdapter cartListAdapter = new CartListAdapter(arrayList, Cart.class);
        recyclerView.setAdapter(cartListAdapter);
    }

    public void fetchData() {
        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                "link/cart/list?user_email="
                        + sharedPreferences.getString("email", ""), new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                parseJSON(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        queue.add(stringRequest);
    }
}


CartListAdapter.java
<pre lang="Java"><pre>
public class CartListAdapter extends RecyclerView.Adapter<CartListAdapter.MyViewClass> {

    ArrayList<ListData> listdata;
    Context context;
    SharedPreferences sharedPreferences;

    public static class MyViewClass extends RecyclerView.ViewHolder {
        TextView textViewCartData;
        TextView itemWeight;
        TextView itemPrice;
        public CardView cardView;


        public MyViewClass(View itemView) {
            super(itemView);
            this.textViewCartData = itemView.findViewById(R.id.textCartData);
            this.itemWeight = itemView.findViewById(R.id.itemWeight);
            this.itemPrice = itemView.findViewById(R.id.itemPrice);
            cardView = itemView.findViewById(R.id.cardView);
        }
    }

    public CartListAdapter(ArrayList<ListData> listdata, Class<Cart> cartClass) {
        this.listdata = listdata;
    }

    @NonNull
    @Override
    public MyViewClass onCreateViewHolder(ViewGroup parent, int viewType) {
        context = parent.getContext();
        sharedPreferences = context.getSharedPreferences("CustomerApp", MODE_PRIVATE);
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row,parent,false);
        MyViewClass myViewClass = new MyViewClass(view);
        return myViewClass;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewClass holder, int position) {
        ListData list = listdata.get(position);
        holder.itemPrice.setText(list.getPrice() + "$");
        holder.textViewCartData.setText(list.getName());
        holder.itemWeight.setText(list.getDes());
    }

    @Override
    public int getItemCount() {
        return listdata.size();
    }

}


What is problem? Please

What I have tried:

I don't know exactly where the problem is.
It says empty value. I understand the problem, I just don't understand.
  Please tell me the correct solution.
Posted
Comments
Richard MacCutchan 5-Mar-23 7:28am    
The solution is to use the debugger to find the offending line of code, and why it is using a null reference.
David Crow 6-Mar-23 8:50am    
There are three places where you are calling the append() method:
textViewCartData.append("Item: " + name + "");
itemWeight.append("Ceki: " + numItem + "");
itemPrice.append("" + price + "");
At least one of them is using a null object.
CoderzF1 27-May-23 19:41pm    
i could tell you exactly which one is null, but you wouldn't learn to use the logcat or debugger. it does tell you the line number of where the error is occurring. there is one of your views that hasnt been initiated in your onCreate function

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900