ListView的整个大小的List都填充了相同的值

时间:2015-09-12 17:05:40

标签: android listview

/*
this is the class which is called when a button is pressed in main activity. onResume is called along with onCreate first, and the list is getting populated with the last row input from the database multiple times.

目的是使用数据库中的表中的数据填充listview。 何时被onResume调用?     * /

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

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class Expenses extends Activity {
    ListView l;Databasehelper mydb;List<ListViewItem> items;
    MyAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_expenses);
        l= (ListView)findViewById(R.id.lv1);
        mydb=new Databasehelper(this);
         items= new ArrayList<Expenses.ListViewItem>();


        //adapter= new MyAdapter(this, items);
        //l.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        items.clear();
        ListViewItem a= new ListViewItem();
        Cursor cur=mydb.getData();
        if(cur.getCount()==0)
            Toast.makeText(this, "No expenses to display", Toast.LENGTH_LONG).show();

        cur.moveToFirst();
        do
        {
            a.category=cur.getString(0);
            a.status=cur.getString(1);
            a.amount=cur.getString(2);
            items.add(a);
        }while(cur.moveToNext());
        adapter= new MyAdapter(this, items);
        l.setAdapter(adapter);
        for(int i=0; i<items.size(); i++)
        {
            System.out.print(items.get(i).category+" "+items.get(i).status+" "+items.get(i).amount);
            System.out.println();
        }

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.expenses, menu);
        return true;
    }

    public class ListViewItem{
        public String category, amount, status;
    }

    public void onAdd(View v){
        Intent in= new Intent(this, Input.class);
        startActivityForResult(in, 10);
    }

}

//请帮助填充表格。我怀疑恢复方法有问题。当我使用print命令打印时,列表包含相同//的多个副本。但是,数据库中的表包含正确的元组

1 个答案:

答案 0 :(得分:1)

问题是你做的循环。在迭代游标时,您使用相同的ListViewItem对象来设置值。您应该在游标的每次迭代中创建一个新的ListViewItem对象。像这样:

    do {
        ListViewItem a = new ListViewItem()
        a.category=cur.getString(0);
        a.status=cur.getString(1);
        a.amount=cur.getString(2);
        items.add(a);
    } while(cur.moveToNext());