Listview repeats the last record inserted in Sqlite across the list

Asked

Viewed 51 times

0

I’m learning how to develop mobile for Android using Java and started studies to persist data. Everything was fine until I tried to fetch the Sqlite data and insert it in a listview: the whole list gets the values of the last data inserted in the Sqlite. below my Fragment which is triggered in the creation of the app and after insertion in the bank:

public class Listar_Produtos extends Fragment {

bancoDAO dao;
ListView lista;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_listar__produtos, container, false);

        dao = new bancoDAO(getContext());
        List<Produto> produtosLst = dao.ListarTodos();
        lista = (ListView) view.findViewById(R.id.LstView);
        ArrayAdapter<Produto> adapter = new ArrayAdapter<Produto>(getContext(), android.R.layout.simple_list_item_1, produtosLst);
        lista.setAdapter(adapter);

        return view;
    }


}

below the method in the bank:

public List<Produto> ListarTodos(){
    db = constructor.getReadableDatabase();
    sql = "select * from "+constructor.TABELA;
    List<Produto> produtosLst = new ArrayList<Produto>();

    cursor = db.rawQuery(sql, null);

    try{
        cursor.moveToFirst();
                for (int i = 0; i < cursor.getCount(); i++){
            //while (cursor.moveToNext()){
                Produto produto = new Produto();

                produto.set_id(cursor.getInt(cursor.getColumnIndexOrThrow("_id")));
                produto.setNome(cursor.getString(cursor.getColumnIndexOrThrow("nome")));
                produto.setTipo(cursor.getString(cursor.getColumnIndexOrThrow("tipo")));
                produto.setComp(cursor.getDouble(cursor.getColumnIndexOrThrow("comp")));
                produto.setLarg(cursor.getDouble(cursor.getColumnIndexOrThrow("larg")));
                produto.setPeso(cursor.getDouble(cursor.getColumnIndexOrThrow("peso")));
                produto.setValor(cursor.getDouble(cursor.getColumnIndexOrThrow("valor")));
                Log.i("Nome "+produto.getNome()+ " ", " ID = "+produto.get_id());
                produtosLst.add(produto);
                cursor.moveToNext();
            }
            cursor.close();
        //}

    }finally {
        db.close();
    }
    int a = produtosLst.size();
    Log.i("Temos no banco ",+a+" inserções de produtos na tabela "+constructor.TABELA);
    return produtosLst;

}

I checked in the database and log that the data in the database is different

waiting for process to come online...
Connected to process 6709 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/cabral.produto: Not late-enabling -Xcheck:jni (already on)
W/cabral.produto: Unexpected CPU variant for X86 using defaults: x86
W/cabral.produto: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
    Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
I/Nome bil2:  ID = 1
I/Nome Lucas:  ID = 2
I/Nome Luciano:  ID = 3
I/Nome Creuza:  ID = 4
I/Nome Luana:  ID = 5
I/Temos no banco: 5 inserções de produtos na tabela produto
D/OpenGLRenderer: HWUI GL Pipeline
D/: HostConnection::get() New Host Connection established 0xec44a4c0, tid 6741
I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/OpenGLRenderer: Swap behavior 0
D/EGL_emulation: eglCreateContext: 0xec452400: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xec452400: ver 2 0 (tinfo 0xe84859f0)
D/EGL_emulation: eglMakeCurrent: 0xec452400: ver 2 0 (tinfo 0xe84859f0)

But that’s all there is to it :

Imagem do emulador

conteúdo direto do SQLite do emulador

Product class:

public class Produto {
    public static int _id;
    public static String Nome;
    public static String Tipo;
    public static double Comp;
    public static double Larg;
    public static double Peso;
    public static double Valor;

    public static int get_id() {
        return _id;
    }

    public static void set_id(int _id) {
        Produto._id = _id;
    }

    public static String getNome() {
        return Nome;
    }

    public static void setNome(String nome) {
        Nome = nome;
    }

    public static String getTipo() {
        return Tipo;
    }

    public static void setTipo(String tipo) {
        Tipo = tipo;
    }

    public static double getComp() {
        return Comp;
    }

    public static void setComp(double comp) {
        Comp = comp;
    }

    public static double getLarg() {
        return Larg;
    }

    public static void setLarg(double larg) {
        Larg = larg;
    }

    public static double getPeso() {
        return Peso;
    }

    public static void setPeso(double peso) {
        Peso = peso;
    }

    public static double getValor() {
        return Valor;
    }

    public static void setValor(double valor) {
        Valor = valor;
    }

    public String toString() {
        return "Nome "+Nome;
    }
}

Guys, does this have anything to do with the standard list template I’m wearing? Someone could give me a light?

  • Adds the code of the Product class.

  • I added the class by editing the post

1 answer

0


The reason all rows have the same value is that the class fields have been declared Static.

A field Static has its value shared by all bodies. Thus, when it is changed, whatever the instance that changes it, this change is reflected in all the others.

The last change is made when the last record of the table where the NAME column has the Luana value is read, so all rows have the value Nome Luana.

Static fields should only represent "class characteristics" and not instance.

On the other hand, fields that identify a particular instance should not be able to be changed after instantiation, so they should not have methods set.
Will be the case of Id and eventually Name and Type, whose values must be assigned to the manufacturer.

  • Thank you @ramaral, I changed all fields removing Static and I will govern the get/set methods and it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.