想要将webview数据从android保存到sqlite

时间:2016-06-07 13:28:11

标签: android sqlite webview

我曾尝试使用javascriptInterface将数据从webview解析为文本视图,以便我可以将文本存储在sqlite中但没有取得成功。我是android的新手所以请指导我如何实现

1 个答案:

答案 0 :(得分:0)

尝试以下代码

final Context myctxt = this; //your activity or application context
    class MyJavaScriptInterface
    {

        @JavascriptInterface
        @SuppressWarnings("unused")
        public void processHTML(String html)
        {
            // process the html as needed by the app
            DBHelpher dbhelpher=new DBHelpher(myctxt);
            dbhelpher.insertHtmlString(html);

        }
    }

    final WebView browser = (WebView)findViewById(R.id.browser);
    /* JavaScript must be enabled if you want it to work, obviously */
    browser.getSettings().setJavaScriptEnabled(true);

    /* Register a new JavaScript interface called HTMLOUT */
    browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

    /* WebViewClient must be set BEFORE calling loadUrl! */
    browser.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url)
        {
            /* This call inject JavaScript into the page which just finished loading. */
            browser.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
        }
    });

    /* load a web page */
    browser.loadUrl("YOUR LINK");


    Create class for sqlite

    public class DBHelpher extends SQLiteOpenHelper 
    {

     Context context;
        public final String TABLE_SAMPLE="test";
          public final String COLUMN_ID="id";
        public final String COLUMN_HTMLSTRING="htmlstring";

        public final String CREATE_TABLE__SAMPLE_SQL="create table " + TABLE_SAMPLE
                + " (" + COLUMN_ID + " integer primary key autoincrement, "
                + COLUMN_HTMLSTRING + " text "
                + ");";


        public DBHelpher(Context context)
        {
            super(context, "DATABASENAME.db", null, 1);
            this.context=context;
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(CREATE_TABLE__SAMPLE_SQL);


        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }


        public void insertHtmlString(String htmlString)
        {

            SQLiteDatabase database = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(COLUMN_HTMLSTRING,htmlString);
             database.insert(TABLE_SAMPLE, null, values);


        }


    }

您将在processHTML方法中获得整个Html contnet。并且它不会再提出网页请求。