如何将数据库打印为表格? (Android,SQLite)

时间:2012-05-13 17:19:30

标签: android sqlite tablelayout

我已经成功创建了一个包含多个表的数据库,并使用rawQuery成功选择了所有表。所有表都相似,我的意思是它们具有不同值的相同列。 现在我需要在一个新的Activity中打印所有表。我想通过在TableLayout中添加行来实现。每个新表格将打印在一个新行中。

请纠正我或表明另一种方式。我是这样做的:

//添加新表格

EditText title = (EditText)findViewById(R.id.Title); 
        String Title = title.getText().toString();

        EditText d = (EditText)findViewById(R.id.director); 
        String Director = d.getText().toString();

                SQLiteDatabase db = openOrCreateDatabase("Films", MODE_PRIVATE, null);
        db.execSQL("CREATE TABLE IF NOT EXISTS " + Title + " (Title VARCHAR, Director VARCHAR);");
        db.execSQL("INSERT INTO " + Title + "(Title) VALUES('" + Title + "');");
        db.execSQL("INSERT INTO " + Title + " (Director) VALUES('" + Director + "');");
        db.close();
        startActivity(new Intent(Add.this, Browse.class));

// SELECTING

SQLiteDatabase db = openOrCreateDatabase("Films", MODE_PRIVATE, null);
     Cursor c = db.rawQuery("SELECT * FROM sqlite_master WHERE type='table'",null);

//在遇到新标题时尝试创建新行

c.moveToFirst();
TableLayout tl = (TableLayout)findViewById(R.id.myTableLayout);
while (c.moveToNext())
     {
         if (c.getString(c.getColumnIndex("Title")) != null)
         {
             String Title = c.getString(c.getColumnIndex("Title"));

             TableRow tr = new TableRow(this);
               tr.setLayoutParams(new LayoutParams(
                              LayoutParams.FILL_PARENT,
                              LayoutParams.WRAP_CONTENT));
                    /* Create a Button to be the row-content. */
                    TextView b = new TextView(this);
                    b.setText(Title);
                    b.setLayoutParams(new LayoutParams(
                              LayoutParams.FILL_PARENT,
                              LayoutParams.WRAP_CONTENT));
                    /* Add Button to row. */
                    tr.addView(b);
             tl.addView(tr,new TableLayout.LayoutParams(
                        LayoutParams.FILL_PARENT,
                        LayoutParams.WRAP_CONTENT));
             c.moveToNext();
         }

但DDMS表示它无法从第1行col -1获得字段插槽。

顺便说一句,我在每个表中只有2列,但CursorWindow说有5列。

请帮忙!

2 个答案:

答案 0 :(得分:3)

您提取的光标只包含一列,即表名,这就是您尝试访问该游标中不存在的列时出现列错误的原因。

您需要使用该游标中的表名来设置循环,以查询每个表的表内容,并使用表内容游标填充您的表。

根据您的操作方式,您可能需要使用MergeCursor。

修改

返回的前两个表是系统表,因此您应该跳过它们并从光标的第三个条目开始。

c.moveToFirst();
c.moveToPosition(3);  // may be two, not sure if the cursor starts at 0 or 1
while (c.isAfterLast == false) {
    String tblName = c.getString(1);
    Cursor table = db.rawQuery("SELECT * FROM " + tblName,null);
    table.moveToFirst();
    if (table.getString(table.getColumnIndex("Title")) != null) {
        //  Your code to create table
    }
    c.moveToNext();
}

答案 1 :(得分:0)

表格在Android中并没有很好地清除,并且比预期更难,所以我在水平文本视图布局下填充普通列表视图的新技巧这里是如何跟随我的领导这是一个从数据库中检索团队分数的表:

主要活动:

public class ViewAllScores extends ListActivity {


@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
 setContentView(R.layout.table_total_scores_by_exam);

        generateTable();

    }private void generateTable() {
        // TODO Auto-generated method stub
        setContentView(R.layout.table_total_scores_by_exam);
        mDbHelper = new DBhelp(this);
        mDbHelper.open();
        String ExamID = "1";
        mNotesCursor = mDbHelper.getAllTeamsScoresByExam(ExamID);

        startManagingCursor(mNotesCursor);

        String[] from = new String[] { mDbHelper.KEY_TEAMS_TEAMNAME,
                mDbHelper.KEY_SCORES_TOTALSCORE,
                mDbHelper.KEY_SCORES_TIMEELAPSED };

        int[] to = new int[] { R.id.tblTablesTeamsByExamRowsTeamName,
                R.id.tblTablesTeamsByExamRowsTeamScore,
                R.id.tblTablesTeamsByExamRowsElapsedTime };
        SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
                R.layout.table_teams_by_exams_rows, mNotesCursor, from, to);

        setListAdapter(notes);

    }

数据库活动:

public Cursor getAllTeamsScoresByExam(String examID) {
        // TODO Auto-generated method stub
        String where = KEY_SCORES_SCOREDEXAMID + "=?";

        String[] whereArgs = new String[] { examID };

        Cursor cursor = ourDatabase.query(VIEW_TEAMS_SCORES_BY_EXAM,
                new String[] { KEY_SCORES_SCOREDEXAMID, KEY_SCORES_TIMEELAPSED,
                        KEY_SCORES_TOTALSCORE ,KEY_SCORES_TEAMTRANSID,
                        KEY_TEAMS_TEAMNAME }, where, whereArgs, null, null,
                KEY_SCORES_TOTALSCORE+" DESC");

        return cursor;
    }

R.layout.table_total_scores_by_exam:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="99" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="33"
            android:background="@drawable/cell_shape"
            android:gravity="center"
            android:text="Team Name"
            android:textSize="30sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="33"
            android:background="@drawable/cell_shape"
            android:gravity="center"
            android:text="Total Score"
            android:textSize="30sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="33"
            android:background="@drawable/cell_shape"
            android:gravity="center"
            android:text="Elapsed Time"
            android:textSize="30sp"
            android:textStyle="bold" />
    </LinearLayout>

    <ListView
        android:id="@+id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

R.layout.table_teams_by_exams_rows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="99" >

    <TextView
        android:id="@+id/tblTablesTeamsByExamRowsTeamName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="33"
        android:background="@drawable/cell_shape"
        android:gravity="center"
        android:text="Team Name"
        android:textSize="22sp"
        />

    <TextView
        android:id="@+id/tblTablesTeamsByExamRowsTeamScore"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="33"
        android:background="@drawable/cell_shape"
        android:gravity="center"
        android:text="Total Score"
        android:textSize="22sp"
        />

    <TextView
        android:id="@+id/tblTablesTeamsByExamRowsElapsedTime"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="33"
        android:background="@drawable/cell_shape"
        android:gravity="center"
        android:text="Elapsed Time"
        android:textSize="22sp"
        />

</LinearLayout>

希望这个技巧有帮助