How do I print database as a table? (Android, SQLite)

こ雲淡風輕ζ 提交于 2020-01-05 07:50:33

问题


I've successfully created a database with several tables in it and successfully selected all the tables with rawQuery. All the tables are similar, I mean they have the same columns with different values. Now I need to print all the tables in a new Activity. I want to do it by adding rows in TableLayout. Each new table will be printed in a new row.

Please, correct me or show another way of doing it. I do it like this:

//ADDING NEW TABLES

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);

//TRYING TO CREATE NEW ROWS WHEN MEET NEW TITLE

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();
         }

But DDMS says it can't get field slot from row 1 col -1.

By the way, I've got only 2 columns in each table, but CursorWindow says there are 5 columns.

Please, help!


回答1:


The cursor you pulled contains only one column, the table names, which is why you're getting the column error when you try to access columns that don't exist in that cursor.

You need to set up a loop using the table names from that cursor to query for the table contents of each table, and use the table contents cursor(s) to fill your table.

Depending on how you do it you might need to use MergeCursor.

EDIT

The first two tables returned are system tables, so you should skip over them and start at the third entry in the cursor.

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:


Table is not well cleared in android and harder than expect so i made a new trick to populate a normal list view under a horizontal text views layouts here is how just follow my lead this is a table that retrieve teams scores from the database :

MAIN ACTIVITY :

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);

    }

DATABASE ACTIVITY :

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>

hope this trick helps



来源:https://stackoverflow.com/questions/10573682/how-do-i-print-database-as-a-table-android-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!