0

I'm creating an app that makes inventaries for the restaurant of my parents. I've been working in the custom view that shows the name of the product and the quantity of it on the current inventary in a listView. Everything works fine until I add a new product to any inventary. After I add the product any time that I go to the that inventary the app crash.

This is visionInventario.java


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;

public class visionInventario extends AppCompatActivity {

    TextView tituloInventario;
    static int positionCurrentInventario;

    static InventarioListAdapter adapter1;


    public void loadData(){
        SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",MODE_PRIVATE);
        Gson gson = new Gson();
        String json = sharedPreferences.getString("task list",null);
        Type type = new TypeToken<ArrayList<Inventario>>(){}.getType();
        Inventarios.InventariosActuales = gson.fromJson(json,type);

        for(int i = 0; i < Inventarios.InventariosActuales.size();i++){
            Inventarios.nombresInventarios.add(Inventarios.InventariosActuales.get(i).nombre);
        }

        if(Inventarios.InventariosActuales == null){
            Inventarios.InventariosActuales = new ArrayList<>();
        }
    }
    public void saveData(){
        SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Gson gson = new Gson();
        String json = gson.toJson(Inventarios.InventariosActuales);
        editor.putString("task list",json);
        editor.apply();
    }
    public void addProductoButton(View view){
        Intent goToAddNewProducto = new Intent(this,addNewProducto.class);
        startActivity(goToAddNewProducto);
    }


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

        //loadData();

        tituloInventario = (TextView) findViewById(R.id.tituloInventario);
        Intent thisIntent = getIntent();
        positionCurrentInventario = thisIntent.getIntExtra("itemPosition",0);

        tituloInventario.setText(Inventarios.nombresInventarios.get(positionCurrentInventario));

        ListView listProductos = (ListView) findViewById(R.id.listaProductos);
        adapter1 = new InventarioListAdapter(this,Inventarios.InventariosActuales.get(positionCurrentInventario).products);

        listProductos.setAdapter(adapter1);


        listProductos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent goToVisionProducto = new Intent(getApplicationContext(),visionProducto.class);
                goToVisionProducto.putExtra("productPosition",position);

                startActivity(goToVisionProducto);
            }
        });

    }
}

This is addNewProducto.java


import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

public class addNewProducto extends AppCompatActivity {
    TextView nombreDelNuevoProducto;

    public void saveData(){
        SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Gson gson = new Gson();
        String json = gson.toJson(Inventarios.InventariosActuales);
        editor.putString("task list",json);
        editor.apply();
    }

    public void AddNewProductoClick(View view){
        producto nuevoProducto = new producto(nombreDelNuevoProducto.getText().toString());
        Inventarios.InventariosActuales.get(visionInventario.positionCurrentInventario).addProduct(nuevoProducto);
        visionInventario.adapter1.notifyDataSetChanged();

        Toast.makeText(this,"¡Producto añadido!", Toast.LENGTH_SHORT).show();

        saveData();

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

        nombreDelNuevoProducto = (TextView) findViewById(R.id.nombreProducto);
    }
}

This is InventarioListAdapter.java

package com.DreamFactory.restaurantcontrol;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

public class InventarioListAdapter extends BaseAdapter {

    Context context;
    ArrayList<producto> arr;

    public InventarioListAdapter(Context context, ArrayList<producto> arr) {
        this.context = context;
        this.arr = arr;
    }

    @Override
    public int getCount() {
        return arr.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View listItemView = convertView;

        if(listItemView == null) {
            listItemView = LayoutInflater.from(context).inflate(R.layout.adapter_view_layout, parent, false);
        }
        TextView quantity = (TextView)convertView.findViewById(R.id.existenciasInventarioVision);
        TextView nameQ = (TextView) convertView.findViewById(R.id.productoInventarioVision);

        quantity.setText(arr.get(position).cantidad);
        nameQ.setText(arr.get(position).nombre);

        return listItemView;
    }
}

This is adapter_view_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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:layout_width="409dp"
        android:layout_height="729dp"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/productoInventarioVision"
            android:gravity="center"
            android:textAlignment="center"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_weight="66.6"
            android:text="TextView" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="33.3"
            android:orientation="vertical">

            <TextView
                android:id="@+id/existenciasInventarioVision"
                android:layout_width="match_parent"
                android:layout_height="61dp"
                android:gravity="center"
                android:text="TextView" />

        </LinearLayout>
    </LinearLayout>
</androidx.constraintlayout.widget.ConstrainLayout>

This is my LogCat when it crashes

2020-04-05 22:49:14.310 17301-17301/com.DreamFactory.restaurantcontrol E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.DreamFactory.restaurantcontrol, PID: 17301
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
        at com.DreamFactory.restaurantcontrol.InventarioListAdapter.getView(InventarioListAdapter.java:52)
  • This is because you are passing the ```null``` object – Marsad Apr 06 '20 at 04:14
  • use listItemView instead of convertView in your findViewById TextViews : TextView quantity = (TextView)listItemView .findViewById(R.id.existenciasInventarioVision); TextView nameQ = (TextView) listItemView .findViewById(R.id.productoInventarioVision); – Farzad Kamali Apr 06 '20 at 04:17
  • You got some variables mixed up in your `Adapter`'s `getView()` method. You meant to make those `findViewById()` calls on `listItemView`, not `convertView`. – Mike M. Apr 06 '20 at 04:18
  • Thanks to Mike M and Farzad Kamali. Now the LogCat comes with a new error: DreamFactory.restaurantcontrol E/AndroidRuntime: FATAL EXCEPTION: main Process: com.DreamFactory.restaurantcontrol, PID: 21843 android.content.res.Resources$NotFoundException: String resource ID #0x0 – Armando Miguel Zegarra Castill Apr 06 '20 at 04:27
  • Looks like you might be calling `setText()` with an integer value somewhere. If so, you need to convert that to a `String` first – e.g., `textView.setText(String.valueOf(whatever));` – because passing an integer means it's a resource ID, which won't be found, and you get that Exception. – Mike M. Apr 06 '20 at 04:45
  • 1
    Mike M. Thanks a lot, You really help me. – Armando Miguel Zegarra Castill Apr 06 '20 at 04:52

0 Answers0