我有一个表,我用SQLite的数据动态创建了这些行。 目前,我在表中只有30条记录,但是当我生成包含手头数据的行时,我只看到28行,其他2行丢失。我从我的Log cat中确认我有30条记录。
XML文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--Table Body-->
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:id="@+id/table_body"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*">
</TableLayout>
</ScrollView>
</LinearLayout>
从SQLite检索作为列表返回的数据的方法。
public List<RosterItem> fetchRoster(){
List<RosterItem> rosterList = new ArrayList<>();
String readQuery = "SELECT * FROM " + RosterTable.NAME;
try{
mDatabase = mHelper.getWritableDatabase();
mDatabase.beginTransaction();
Cursor cursor = mDatabase.rawQuery(readQuery, null);
//Looping through each row and adding to list
if(cursor.moveToFirst()){
do{
RosterItem rosterItem = new RosterItem();
rosterItem.setSyncNumber(cursor.getInt(cursor.getColumnIndex(RosterTable.Cols.SYNC_NUMBER)));
rosterItem.setDate(cursor.getString(cursor.getColumnIndex(RosterTable.Cols.DATE)));
rosterItem.setShift(cursor.getString(cursor.getColumnIndex(RosterTable.Cols.SHIFT)));
//Add to list
rosterList.add(rosterItem);
}while(cursor.moveToNext());
cursor.close();
}
mDatabase.setTransactionSuccessful();
}catch(SQLiteException e){
e.printStackTrace();
}finally {
mDatabase.endTransaction();
}
mDatabase.close();
return rosterList;
}
使用数据的片段。
List<RosterItem> allRosters = dbAdapter.fetchRoster(); // Check for possibility of empty array b4
Log.d(TAG, "Number of items " + allRosters.size());
for(RosterItem roster: allRosters){
Log.d(TAG, "" +roster.getSyncNumber());
//Generate contents of table (Table Body)
int rosterNumber = roster.getSyncNumber();
String rosterDate = roster.getDate();
String rosterShift = roster.getShift();
//Generate table rows
TableRow row = new TableRow(getContext());
//Set parameters
TableRow.LayoutParams tabParams = new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tabParams.setMargins(2,2,2,2);
row.setLayoutParams(tabParams); //Necessary in order to be able to set the margins
String[] colText = {rosterNumber+"", rosterDate, rosterShift};
for(String text:colText){
TextView tv = new TextView(getContext());
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tv.setGravity(Gravity.CENTER);
tv.setTextSize(16);
tv.setPadding(5,5,5,5);
tv.setText(text);
tv.setBackgroundColor(Color.WHITE);
tv.setLayoutParams(tabParams);
row.addView(tv);
}
mTableBody.setBackgroundColor(Color.BLACK);
mTableBody.addView(row);
}
屏幕截图显示here