我的数据库全部设置并运行。但是现在我遇到的问题是将它加载到listview中。我在网站上尝试了其他问题但没有回答我的问题。从初学者(ish)的角度来看。如何将数据库加载到listview中?
这是我班上的内容:(显示类位于底部)
public class Inventory extends Activity {
DBAdapter db = new DBAdapter(this);
private Cursor cursor = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inventory_screen);
try {
String destPath = "/data/data/" + getPackageName()
+ "/databases/InventoryDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB(getBaseContext().getAssets().open("InventoryDB"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
DBAdapter db = new DBAdapter(this);
try {
db.open();
Cursor c = db.getAllRecords();
if (c.moveToFirst()) {
do {
DisplayRecord(c);
} while (c.moveToNext());
}
db.close();
} catch (Exception e) {
Log.e("ERROR", "ERROR IN CODE:" + e.toString());
e.printStackTrace();
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
// ---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
// List View
public void DisplayRecord(Cursor c) {
ListView InventoryItems = (ListView) findViewById(R.id.listViewInventory);
String[] Items = new String[] {c.getString(1)};
ArrayAdapter<String> ItemsAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, Items);
InventoryItems.setAdapter(ItemsAdapter);
//Toast msg = Toast.makeText(Inventory.this, "id: " + c.getString(0)
// + "\n" + "Item: " + c.getString(1) + "\n", Toast.LENGTH_SHORT);
//msg.show();
}
我只是设置了一个列表视图来拉动数据库中的第一项(这就是我的所有知识延伸到了)
我如何显示所有数据?我听说过simpleCursorAdapter,但我不知道这是否相关?
答案 0 :(得分:0)
尝试这个:
public void display()
{
ListView lv=(ListView)findViewById(R.id.listView1);
String from[] = new String[] {db.KEY_DATE,db.KEY_DESC,db.KEY_INCOME,db.KEY_ROWID};
int to[] = new int[] {R.id.text1 ,R.id.text3,R.id.text5,R.id.text9};
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.columnview, c, from, to)
{
@Override
public void bindView(View view, Context context, Cursor cursor)
{
text1.setText(cursor.getString(cursor.getColumnIndex(db.KEY_DATE)));
text5.setText(cursor.getString(cursor.getColumnIndex(db.KEY_INCOME)));
text9.setText(cursor.getString(cursor.getColumnIndex(db.KEY_ROWID)));
Set to the textview according to your requirement..
};
lv.setAdapter(notes);
}