使用ArrayList填充动态创建的ListView

时间:2012-05-28 14:15:26

标签: android arraylist android-listview listactivity

我正在尝试使用从另一个函数获取的ListView来填充动态创建的ArrayList。我收到错误"The constructor ArrayAdapter<String>(ShowRecords, ListView, ArrayList<String>) is undefined"。这是ListActivity的代码:

public class ShowRecords extends ListActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);

        DatabaseHandler db = new DatabaseHandler(this);
        ArrayList<String> records = db.getRecords();

        ListView lv = new ListView(this);
        this.setListAdapter(new ArrayAdapter<String>(this, lv, records));
    } 

}

这是getRecords()函数的代码:

public ArrayList<String> getRecords() {
    ArrayList<String> recordList = new ArrayList<String>();
    String selectQuery = "SELECT millis FROM records ORDER BY CAST(millis as SIGNED) DESC LIMIT 10";

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {
                recordList.add(cursor.getString(0));
            } while (cursor.moveToNext());
        }
    }

    return recordList;
}

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

由于您使用的是ListActivity,因此无需声明listview。

试试这个,这应该有效!

public class ShowRecords extends ListActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);

    DatabaseHandler db = new DatabaseHandler(this);
    ArrayList<String> records = db.getRecords();
    setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, records));
} 

}

答案 1 :(得分:0)

以下是可用构造函数列表:

[Public Method] [Constructor] ArrayAdapter(Context, int) : void
[Public Method] [Constructor] ArrayAdapter(Context, int, int) : void
[Public Method] [Constructor] ArrayAdapter(Context, int, Object[]) : void
[Public Method] [Constructor] ArrayAdapter(Context, int, List) : void
[Public Method] [Constructor] ArrayAdapter(Context, int, int, List) : void
[Public Method] [Constructor] ArrayAdapter(Context, int, int, Object[]) : void

你当然想要使用这个:

[Public Method] [Constructor] ArrayAdapter(Context, int, Object[]) : void

所以这意味着:

this.setListAdapter(new ArrayAdapter<String>(this, R.id.whateveridyouchoose, records));