3

Tenho uma listView que lista através de um adapter. A lista é atualizada atrqavés de uma pesquisa no SQLite. O problema é que só aparece apartir do segundo elemento da minha tabela.... alguem poderia me ajudar?

Adapter:

public class ItemListHistoryAdapter extends BaseAdapter {

    private Context ctx;
    private List<ItemListHistory> listItem;

    public ItemListHistoryAdapter(Context context, List<ItemListHistory> listItem){

        this.ctx = context;
        this.listItem = listItem;

    }

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

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

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

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

        //Layout que vai retornar
        View layoutReturn;

        if (convertView == null) {

            LayoutInflater inflaterHelper = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            layoutReturn = inflaterHelper.inflate(R.layout.layout_list, null);


            convertView = inflaterHelper.inflate(R.layout.layout_list, null);
        }else {
            layoutReturn = convertView;
        }

        TextView tvScore = (TextView) layoutReturn.findViewById(R.id.ll_tv_score);
        if (Integer.parseInt(listItem.get(position).getTxtScore())>0){
            tvScore.setTextColor(ctx.getResources().getColor(R.color.deepskyblue));
        }else{
            tvScore.setTextColor(ctx.getResources().getColor(R.color.red));
        }
        tvScore.setText("Score: "+listItem.get(position).getTxtScore());

        TextView tvDate = (TextView) layoutReturn.findViewById(R.id.ll_tv_date);
        tvDate.setText(listItem.get(position).getTxtDate());

        ImageView ivCool = (ImageView) layoutReturn.findViewById(R.id.ll_iv_cool);
        ivCool.setImageResource(listItem.get(position).getIconId());

        return layoutReturn;
    }
}

Activity:

public class HistoryActivity extends Activity {

    private List<ItemListHistory> listItens;
    SQLiteOpenHelper dbHelper = new HistorySQLHelper(this);

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

        //alterando a fonte do Titulo da Activity
        FontManager fontManager = new FontManager();
        TextView tvTitle = (TextView) findViewById(R.id.hi_tv_title);
        fontManager.changeFontTextView(this, tvTitle, fontManager.BLOODLUST_PATH);

        //meu banco de dados
        final SQLiteDatabase db = dbHelper.getWritableDatabase();

        //List View
        ListView lvHistory = (ListView) findViewById(R.id.hi_lv_list);

        listItens = findAllItens(db);

        //Adapter
        final ItemListHistoryAdapter listAdapter = new ItemListHistoryAdapter(this, listItens);
        lvHistory.setAdapter(listAdapter);

    }

    //retorna uma lista de itens do banco de dados
    private List<ItemListHistory> findAllItens(SQLiteDatabase db){
        int imageRId;

        db = dbHelper.getWritableDatabase();

        String sqlQuery = "SELECT * FROM "+HistorySQLHelper.TAB_HISTORY+" ORDER BY "+HistorySQLHelper.COLUMN_DATE+" DESC;";
        List<ItemListHistory> listItens = new ArrayList<ItemListHistory>();

        Cursor cursor = db.rawQuery(sqlQuery,null);
        cursor.moveToFirst();

        while (cursor.moveToNext()){
            String score = cursor.getString(cursor.getColumnIndex(HistorySQLHelper.COLUMN_SCORE));

            String date = cursor.getString(cursor.getColumnIndex(HistorySQLHelper.COLUMN_DATE));


            if (Integer.parseInt(score) < 0){
                imageRId = R.drawable.monster2;
            }else{
                imageRId = R.drawable.coin_gold;
            }

            ItemListHistory itemListHistory = new ItemListHistory(score,date,imageRId);

            listItens.add(itemListHistory);
        }
        cursor.close();
        db.close();

        return listItens;
    }

    public void clearRanking(View view){

        AlertDialog.Builder dialog = new AlertDialog.Builder(HistoryActivity.this);

        dialog.setMessage(R.string.msg_really);
        dialog.setTitle(R.string.msg_title_attention);
        dialog.setIcon(R.drawable.warning);
        dialog.setPositiveButton(R.string.bt_yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                SQLiteOpenHelper dbHelper = new HistorySQLHelper(getBaseContext());
                SQLiteDatabase db = dbHelper.getWritableDatabase();

                String sql = "DELETE FROM " + HistorySQLHelper.TAB_HISTORY + "";
                db.execSQL(sql);
                db.close();
                Toast.makeText(getBaseContext(), "Ranking clear...", Toast.LENGTH_SHORT).show();
                finish();

            }
        });
        dialog.setNegativeButton(R.string.bt_no, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    public void closeActivity(View view){
        finish();
    }

}

1 Resposta 1

7

Analisando a seguinte parte do seu código:

Cursor cursor = db.rawQuery(sqlQuery,null);
cursor.moveToFirst();

while (cursor.moveToNext()){

    .....
    .....
}

verifica-se que cursor é posicionado no primeiro registo através cursor.moveToFirst();.

Depois, no while, o cursor é posicionado no próximo registo, ao ser feito cursor.moveToNext(), sendo o primeiro registo ignorado.

Elimine a linha cursor.moveToFirst();.

Edit após o meu comentário

A forma mais correcta será:

Cursor cursor = db.rawQuery(sqlQuery,null);
if(cursor != null && cursor.moveToFirst()){
    do{
        .....
        .....
    }while(cursor.moveToNext());
}
4
  • muito obrigado!!!! funcionou, mas para tornar o código mais legivel acho que vou colocar um do-while e continuar com o moveToFirst. 2/07/2015 às 16:43
  • Não esqueça que deve verificar se o cursor não é nulo e que cursor.moveToFirst() retorna true antes de entrar no do-while
    – ramaral
    2/07/2015 às 17:52
  • ;-) Valeu demais 2/07/2015 às 18:00
  • Ainda bem que pude ajudar. Veja aqui a forma de proceder quando uma resposta te foi útil.
    – ramaral
    2/07/2015 às 18:01

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .