【问题标题】:How do I print database as a table? (Android, SQLite)如何将数据库打印为表格? (安卓、SQLite)
【发布时间】:2012-05-13 17:19:30
【问题描述】:

我已经成功地创建了一个包含多个表的数据库,并成功地使用 rawQuery 选择了所有表。所有表都是相似的,我的意思是它们具有不同值的相同列。 现在我需要打印一个新活动中的所有表格。我想通过在 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));

//选择中

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 列。

请帮忙!

【问题讨论】:

  • 为什么不使用像 ORMLite 这样无需编写 SQL 的好框架呢? :)
  • 我需要使用 SQLite,因为我的老师问我。我会阅读 ORMLite,因为它很有趣,谢谢,但我必须使用 SQLite 来完成它。

标签: android sqlite tablelayout


【解决方案1】:

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

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

根据您的操作方式,您可能需要使用 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();
}

【讨论】:

    【解决方案2】:

    表格在 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>
    

    希望这个技巧有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多