我试图用SQL数据库中的数据填充listview,使用以下代码
final DBAdapter db = new DBAdapter(this);
db.open();
Cursor c = db.getAsset6("MARK BARR");
int mx=1;
String[] lvdata = new String[mx];
while (c.moveToNext()) {
lvdata[mx]=c.getString(1) + "-" + c.getString(2) + "-" + c.getString(6);
mx++;
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, lvdata));
getListView().setTextFilterEnabled(true);
db.close();
当我运行应用程序崩溃时,我确信这与我在while循环中将数据添加到字符串中然后设置适配器的方式有关,但我无法找出我出错的地方
感谢您的帮助
标记编辑OK下面的工作正常,但是当我到达最后一个listview条目
时,应用程序崩溃了 final DBAdapter db = new DBAdapter(this);
db.open();
Cursor c = db.getAsset6("MARK BARR");
int mx=0;
String[] lvdata = new String[c.getCount()];
while (c.moveToNext()) {
lvdata[mx]=c.getString(1) + "-" + c.getString(2) + "-" + c.getString(6);
mx++;
}
// use your custom layout
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.rowlayout, R.id.label, lvdata);
setListAdapter(adapter);
}
我可能连给Vogella系鞋带的资格都没有,但我就是这么做的。我喜欢使用CursorAdapter,因为它允许你对图像做各种事情,我认为它更容易。如果你不使用这个,请检查它,因为你可能需要这个在未来。把它放在你想要查看数据的地方,无论是在onCreate中还是从某个按钮被按下。
SQLiteDatabase sqLiteDatabase = controller.getReadableDatabase();
String query = "SELECT DISTINCT * FROM YOURTABLENAME";
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
((ListView) YOURLISTVIEWNAME).setAdapter(new ANYNAMEADAPTER(context,
cursor, 0));
然后我们创建ANYNAMEADAPTER将所有的数据放到一个有组织的地方
private static final class ANYNAMEADAPTER extends CursorAdapter {
ANYNAMEADAPTER(Context context, Cursor cursor, int flags) {
super(context, cursor, flags);
mInflater = LayoutInflater.from(context);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
return v;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView theline = (TextView) view.findViewById(android.R.id.text1);
String thedata =cursor.getString(1) + "-" + cursor.getString(2) + "-" + cursor.getString(6);
theline.setText(thedata);
}
LayoutInflater mInflater;
}