You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中HTML打印表格的For循环实现问题求助

Solution to Generate HTML Table Rows from Android Cursor for Printing

Hey there! I see you're trying to loop through your database cursor to populate an HTML table for printing—let's get this sorted out for you. The main issue in your current code is that you're only fetching a single row's data instead of building all table rows in the loop, and your cursor traversal logic has an off-by-one error (cursor positions start at 0, not 1).

Here's the revised version of your doWebViewPrint() method with proper loop logic to generate all table rows:

private void doWebViewPrint() {
    // Create a WebView object specifically for printing
    WebView webView = new WebView(this);
    final Cursor c = mDatabase.rawQuery("SELECT * FROM " + Contract.Entry.TABLE_NAME, null);
    
    // Use StringBuilder to efficiently build table rows (better than string concatenation)
    StringBuilder tableRows = new StringBuilder();
    
    if (c.moveToFirst()) { // Move to the first row, return false if cursor is empty
        do {
            // Get values from current cursor row
            String name = c.getString(c.getColumnIndex(Contract.Entry.COLUMN_NAME));
            String amount = c.getString(c.getColumnIndex(Contract.Entry.COLUMN_AMOUNT));
            String dose = c.getString(c.getColumnIndex(Contract.Entry.COLUMN_DOSE));
            
            // Append a new table row with the data
            tableRows.append("<tr>")
                    .append("<td>").append(name).append("</td>")
                    .append("<td>").append(amount).append("</td>")
                    .append("<td>").append(dose).append("</td>")
                    .append("</tr>\n");
        } while (c.moveToNext()); // Keep looping until there are no more rows
    }
    
    // Don't forget to close the cursor to avoid memory leaks!
    c.close();

    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onPageFinished(WebView view, String url) {
            Log.i(patintNametv.getText().toString(), "page finished loading " + url);
            createWebPrintJob(view);
            mWebView = null;
        }
    });

    // Generate an HTML document on the fly, inserting our built table rows
    String htmlDocument = "<html><body><!-- Required meta tags -->\n"
            + "<p>&nbsp;</p>\n"
            + "<div>\n"
            + "<div class=\"head\" style=\"direction: rtl; text-align: center; width: 70%;\">\n"
            + "<h5 style=\"padding: -20px;\">Doctor</h5>\n"
            + "<h4>soso al asoli</h4>\n"
            + "<h5>example</h5>\n"
            + "<h5> example</h5>\n"
            + "<ul style=\"list-style-type: circle;\">\n"
            + "<li>الاسم</li>\n"
            + "<li>العمر</li>\n"
            + "<li>التاريخ\n"
            + "<table>\n"
            + "<tbody>\n"
            + "<tr>\n"
            + "<td>الاسم</td>\n"
            + "<td>الكمية</td>\n"
            + "<td>الجرعة;</td>\n"
            + "</tr>\n"
            + tableRows.toString() // Insert all our generated table rows here
            + "</tbody>\n"
            + "</table>\n"
            + "</li>\n"
            + "</ul>\n"
            + "</div>\n"
            + "<div>&nbsp;</div>\n"
            + "<div>\n"
            + "<div>phone:0780801245</div>\n"
            + "<div>location:location</div>\n"
            + "<div>some note here</div>\n"
            + "</div>\n"
            + "</div></body></html>";

    webView.loadDataWithBaseURL(null, htmlDocument, "text/HTML", "UTF-8", null);
    mWebView = webView;
}

Key Changes Explained:

  • Cursor Traversal: Used moveToFirst() and a do-while loop to safely iterate through all rows (this handles empty cursors gracefully too).
  • StringBuilder: Efficiently builds all table rows instead of repeated string concatenation, which is better for performance especially with large datasets.
  • Cursor Cleanup: Added c.close() to release cursor resources and prevent memory leaks.
  • Inserting Rows: The built tableRows string is inserted directly into the HTML table's <tbody> section, replacing your single hardcoded row.

This will generate a table row for every record returned by your database query, which will then be rendered in the WebView and sent to the printer.

内容的提问来源于stack exchange,提问作者SoftLearn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:12:06