My code only takes the last element of the database

Asked

Viewed 48 times

-5

My code only takes the last element of the database, but it lists the correct amount there and the log.i shows that is catching all. Why it does not work?

package br.app.lista;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

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

public class CatalogoTodos extends Activity {

    private Livro livro;
    private Catalogo_Livro_Lista catalogoListaTodos;
    private ListView listTodosCatalogoId;
    private SQLiteDatabase db;
    private  SimpleCursorAdapter ad;
    //private String[] aaa = {"teste","teste1","teste","teste1","teste","teste1","teste","teste1","teste","teste1","teste","teste1"};




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

        listTodosCatalogoId =  (ListView) findViewById(R.id.listTodosCatalogoId);
        db = DBHelper.getDatabase(this,"livro");
        livro = new Livro();

        String listar = "SELECT * FROM livro";
        Cursor cursor = db.rawQuery(listar,null);
        ArrayList<Livro> lv = new ArrayList<Livro>();

        if(cursor.getCount() >0){

            while (cursor.moveToNext()){
                livro.setIsbn(cursor.getString(0));
                livro.setTitulo(cursor.getString(1));
                livro.setSubTitulo(cursor.getString(2));
                livro.setEdicao(cursor.getInt(3));
                livro.setAutor(cursor.getString(4));
                livro.setPaginas(cursor.getInt(5));
                livro.setAnoPublicacao(cursor.getInt(6));
                livro.setEditora(cursor.getString(7));
                livro.setCategoria(cursor.getString(8));
                lv.add(livro);

                Log.i("RESULTADO -" , "TITULO: " + cursor.getString(0));
                Log.i("RESULTADO -" , "AUTOR: " + cursor.getString(4));

            }
            catalogoListaTodos = new Catalogo_Livro_Lista(CatalogoTodos.this,lv);
           // ArrayAdapter<Livro> livroadapter = new ArrayAdapter<Livro>(CatalogoTodos.this,android.R.layout.simple_list_item_1,lv);
            listTodosCatalogoId.setAdapter(catalogoListaTodos);


        }else{
            Toast.makeText(CatalogoTodos.this, "Nenhum registro encontrado", Toast.LENGTH_SHORT).show();

        }

    }

    public void voltarCatalogoTodos (View botao){
        startActivity(new Intent(this, Catalogo.class));
        finish();
    }


}
package br.app.lista;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;


public class Catalogo_Livro_Lista extends BaseAdapter {
    private List<Livro> livros;
    private Activity activity;

    public Catalogo_Livro_Lista(Activity activity, List<Livro> livros) {
        this.livros = livros;
        this.activity = activity;
    }

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

    @Override
    public Object getItem(int position) {
        return  livros.get(position);

    }

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

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        Livro livro =  livros.get(position);
        LayoutInflater inflater = activity.getLayoutInflater();
        View linha = inflater.inflate(R.layout.catalogo_livros_list,null);
        TextView nomeLivro = (TextView) linha.findViewById(R.id.txtNomeLivroId);
        TextView autor = (TextView) linha.findViewById(R.id.txtAutorLivroId);
        ImageView fotoLivro = (ImageView) linha.findViewById(R.id.imgLivrosId);

        nomeLivro.setText(livro.getTitulo());
        autor.setText(String.valueOf(livro.getAnoPublicacao()));

        if(livro.getImagemLivro()!= null){

            Bitmap imglivro = BitmapFactory.decodeFile(livro.getImagemLivro());
            fotoLivro.setImageBitmap(imglivro);


        }else{

            Drawable draw = activity.getResources().getDrawable(R.drawable.lupa);
            fotoLivro.setImageDrawable(draw);

        }


        return linha;

    }
}
  • 3

    Take a read on [Ask]

  • Almost duplicate: https://answall.com/q/238627/132

1 answer

4

How often do you urge your class Livro?

Answer: One. Soon, you have only one book!

The place where you live is here:

        livro = new Livro();

That’s the single place where you give a new Livro(). As this is not within the loop, then only one book was created.

Within the while you do that:

            while (cursor.moveToNext()){
                livro.setIsbn(cursor.getString(0));
                livro.setTitulo(cursor.getString(1));
                livro.setSubTitulo(cursor.getString(2));
                livro.setEdicao(cursor.getInt(3));
                livro.setAutor(cursor.getString(4));
                livro.setPaginas(cursor.getInt(5));
                livro.setAnoPublicacao(cursor.getInt(6));
                livro.setEditora(cursor.getString(7));
                livro.setCategoria(cursor.getString(8));
                lv.add(livro);

                Log.i("RESULTADO -" , "TITULO: " + cursor.getString(0));
                Log.i("RESULTADO -" , "AUTOR: " + cursor.getString(4));

            }

I mean, you are altering the book set instead of being creating a new book. What you should do is something like this:

            while (cursor.moveToNext()) {
                Livro livro = new Livro(); // <--- Observe essa linha.
                livro.setIsbn(cursor.getString(0));
                livro.setTitulo(cursor.getString(1));
                livro.setSubTitulo(cursor.getString(2));
                livro.setEdicao(cursor.getInt(3));
                livro.setAutor(cursor.getString(4));
                livro.setPaginas(cursor.getInt(5));
                livro.setAnoPublicacao(cursor.getInt(6));
                livro.setEditora(cursor.getString(7));
                livro.setCategoria(cursor.getString(8));
                lv.add(livro);

                Log.i("RESULTADO -" , "TITULO: " + cursor.getString(0));
                Log.i("RESULTADO -" , "AUTOR: " + cursor.getString(4));
            }

Remove those two lines that are outside the for:

    private Livro livro;
        livro = new Livro();

That should solve your problem.

I also suggest you change that:

        ArrayList<Livro> lv = new ArrayList<Livro>();

That’s why:

        List<Livro> lv = new ArrayList<>();

There are other problems and possible improvements in your code, but not to get too repetitive, see this other answer of mine in another question similar to yours, especially the part about avoiding empty builders and about mixing visualization logic (Toast.makeText(...)) with database query logic.

  • Good afternoon Victor.. vlw for the tips and the comment. so I made all these changes, I made a smaller and simpler code to see better where I’m going wrong, However the error persists, I’m using the Android Studio IDE and I think it should be a bug, because I made the Android eclipse at the facul and ran... Very grateful

Browser other questions tagged

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