ListView 与自定义适配器在添加新项后崩溃?

huangapple 未分类评论49阅读模式
英文:

ListView with custom adapter is crashing after adding a new item?

问题

以下是翻译好的代码部分:

visionInventario.java

package com.DreamFactory.restaurantcontrol;

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 {

    // ... (省略其他代码)

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

        // ...

        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);
            }
        });
    }
}

addNewProducto.java

package com.DreamFactory.restaurantcontrol;

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 {
    // ... (省略其他代码)

    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);
    }
}

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.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;

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) listItemView.findViewById(R.id.existenciasInventarioVision);
        TextView nameQ = (TextView) listItemView.findViewById(R.id.productoInventarioVision);

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

        return listItemView;
    }
}

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.ConstraintLayout>

LogCat 错误信息

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)
英文:

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(&quot;shared preferences&quot;,MODE_PRIVATE);
        Gson gson = new Gson();
        String json = sharedPreferences.getString(&quot;task list&quot;,null);
        Type type = new TypeToken&lt;ArrayList&lt;Inventario&gt;&gt;(){}.getType();
        Inventarios.InventariosActuales = gson.fromJson(json,type);

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

        if(Inventarios.InventariosActuales == null){
            Inventarios.InventariosActuales = new ArrayList&lt;&gt;();
        }
    }
    public void saveData(){
        SharedPreferences sharedPreferences = getSharedPreferences(&quot;shared preferences&quot;,MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Gson gson = new Gson();
        String json = gson.toJson(Inventarios.InventariosActuales);
        editor.putString(&quot;task list&quot;,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(&quot;itemPosition&quot;,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&lt;?&gt; parent, View view, int position, long id) {
                Intent goToVisionProducto = new Intent(getApplicationContext(),visionProducto.class);
                goToVisionProducto.putExtra(&quot;productPosition&quot;,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(&quot;shared preferences&quot;,MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Gson gson = new Gson();
        String json = gson.toJson(Inventarios.InventariosActuales);
        editor.putString(&quot;task list&quot;,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,&quot;&#161;Producto a&#241;adido!&quot;, 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&lt;producto&gt; arr;

    public InventarioListAdapter(Context context, ArrayList&lt;producto&gt; 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

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;&gt;

    &lt;LinearLayout
        android:layout_width=&quot;409dp&quot;
        android:layout_height=&quot;729dp&quot;
        android:orientation=&quot;horizontal&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot;&gt;

        &lt;TextView
            android:id=&quot;@+id/productoInventarioVision&quot;
            android:gravity=&quot;center&quot;
            android:textAlignment=&quot;center&quot;
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;60dp&quot;
            android:layout_weight=&quot;66.6&quot;
            android:text=&quot;TextView&quot; /&gt;

        &lt;LinearLayout
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;match_parent&quot;
            android:layout_weight=&quot;33.3&quot;
            android:orientation=&quot;vertical&quot;&gt;

            &lt;TextView
                android:id=&quot;@+id/existenciasInventarioVision&quot;
                android:layout_width=&quot;match_parent&quot;
                android:layout_height=&quot;61dp&quot;
                android:gravity=&quot;center&quot;
                android:text=&quot;TextView&quot; /&gt;

        &lt;/LinearLayout&gt;
    &lt;/LinearLayout&gt;
&lt;/androidx.constraintlayout.widget.ConstrainLayout&gt;

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 &#39;android.view.View android.view.View.findViewById(int)&#39; on a null object reference
        at com.DreamFactory.restaurantcontrol.InventarioListAdapter.getView(InventarioListAdapter.java:52)

huangapple
  • 本文由 发表于 2020年4月6日 12:10:27
  • 转载请务必保留本文链接:https://java.coder-hub.com/61052840.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定