android webview仅在第二次刷新/加载后显示加载的数据

时间:2014-08-17 19:05:09

标签: android webview

我正在尝试编写android webview代码来从url中加载来自jason文件的数据。但是,我注意到初始时间页面上没有显示数据,但是如果我单击按钮加载/刷新数据再次页面(不确定是否是因为刷新或重新加载),则会成功显示。我检查了日志文件。第一次单击将以下内容输出到日志中。

08-17 16:07:38.784: V/webview(17435):  singleCursorHandlerTouchEvent -getEditableSupport  FASLE 
08-17 16:07:39.184: V/webview(17435): doShortPress : mNativeClass - 2089760 mPreventDefault -  2
08-17 16:07:41.777: V/webview(17435):  singleCursorHandlerTouchEvent -getEditableSupport  FASLE 
08-17 16:07:42.187: V/webview(17435): doShortPress : mNativeClass - 2089760 mPreventDefault -  2
08-17 16:07:42.588: D/dalvikvm(17435): GC_CONCURRENT freed 375K, 46% free 3455K/6343K, external 377K/1281K, paused 2ms+2ms

第二次运行时会在log中显示以下文本,我们可以看到输出到最后一行日志的已加载字符串数据。

08-17 16:07:51.837: V/webview(17435):  singleCursorHandlerTouchEvent -getEditableSupport  FASLE 
08-17 16:07:52.247: V/webview(17435): doShortPress : mNativeClass - 2089760 mPreventDefault -  2
08-17 16:07:55.901: V/webview(17435):  singleCursorHandlerTouchEvent -getEditableSupport  FASLE 
08-17 16:07:56.301: V/webview(17435): doShortPress : mNativeClass - 2089760 mPreventDefault -  2
08-17 16:07:56.501: D/dalvikvm(17435): GC_FOR_MALLOC freed 117K, 46% free 3472K/6343K, external 377K/1281K, paused 15ms
08-17 16:07:56.501: I/dalvikvm-heap(17435): Grow heap (frag case) to 6.195MB for 87396-byte allocation
08-17 16:07:56.521: D/dalvikvm(17435): GC_FOR_MALLOC freed 32K, 46% free 3525K/6471K, external 377K/1281K, paused 16ms
08-17 16:07:56.591: I/my call:(17435): <ul data-role='listview'><li>abc<p style='font-size:1 font-color:grey'>2014-08-11</p></li><li>def<p style='font-size:1 font-color:grey'>2014-08-14</p></li><li>fgh<p style='font-size:1 font-color:grey'>2014-08-14</p></li><li>hijk<p style='font-size:1 font-color:grey'>2014-08-15</p></li></ul>

有人能说出为什么第一次没带数据吗?请帮忙。感谢。

以下是我的活动代码。

@SuppressLint("SetJavaScriptEnabled")
public class MessageActivity extends Activity {

    WebView mWebView;
    public static String liststr = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);



        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.addJavascriptInterface(new JavaScriptInterface(), "jsinterface");

        mWebView.loadUrl("file:///android_asset/index.html");
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.destroy();
            finish();        
            mWebView.destroy();
            return true;
        }
        else if (keyCode == KeyEvent.KEYCODE_BACK){
            mWebView.destroy();
            finish();   
            mWebView.destroy();
        }
        return super.onKeyDown(keyCode, event);
    }

    private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
        protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {

            InputStream in = entity.getContent();

            StringBuffer out = new StringBuffer();
            int n = 1;
            while (n>0) {
                byte[] b = new byte[4096];

                n =  in.read(b);

                if (n>0) out.append(new String(b, 0, n));

            }

            return out.toString();

        }

        @Override

        protected String doInBackground(Void... params) {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpGet httpGet = new HttpGet("http://****/Post.json");
            String text = null;
            try {

                HttpResponse response = httpClient.execute(httpGet, localContext);

                HttpEntity entity = response.getEntity();

                text = getASCIIContentFromEntity(entity);

            } catch (Exception e) {
                return e.getLocalizedMessage();

            }

            return text;

        }

        protected void onPostExecute(String results) {

            getJsonData(results);

        }

        protected void getJsonData (String jsonstr) {
            JSONArray postarr = new JSONArray();
            liststr = "<ul data-role='listview'>";

            try {
                JSONObject posts = (new JSONObject(jsonstr).getJSONObject("posts"));
                postarr = posts.getJSONArray("post");

                for (int i=0; i<postarr.length(); i++) {
                    JSONObject p = postarr.getJSONObject(i);
                    liststr += "<li>";
                    liststr += p.getString("title");
                    liststr += "<p style='font-size:1 font-color:grey'>";
                    liststr += p.getString("date");
                    liststr += "</p>";
                    liststr += "</li>";
                }
                liststr += "</ul>";
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

    public class JavaScriptInterface {
        String str;

        @JavascriptInterface
        public String getPostValue() {
            new LongRunningGetIO().execute();
            this.str = liststr;
            return str;
        }
    }
}

我的index.html页面。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>LoadPageTest</title>
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,700">
    <link rel="stylesheet" href="./css/customizedstyle.css">
    <link rel="stylesheet" href="./css/themes/default/jquery.mobile-1.4.3.min.css">
    <link rel="stylesheet" href="./css/jqm-demos.css">
    <script src="./js/jquery.js"></script>
    <script scr="./js/customizedjs.js"></script>
    <script src="./js/jquery.mobile-1.4.3.min.js"></script>
    <script>
        $( document ).on( "pagecreate", "#demo-page", function() {

            $( document ).on( "swipeleft swiperight", "#demo-page", function( e ) {
                if ( $( ".ui-page-active" ).jqmData( "panel" ) !== "open" ) {
                    if ( e.type === "swipeleft" ) {
                        $( "#right-panel" ).panel( "open" );
                    } 
                }
            });
        });
        </script>

    <style type="text/css">
    body {
        overflow:hidden;
    }
    </style>
</head>
<body style= "overflow:hidden" scrolling="no">

<style type="text/css">
body {
    overflow:hidden;
}
</style>


<div data-role="page" id="main-page" style= "overflow:hidden" scrolling="no">

    <div role="main" class="ui-content" id ="maindiv" style= "overflow: auto">

        Will load diff pages here.

    </div><!-- /content -->

    <div data-role="panel" id="left-panel" data-theme="b">

        <ul data-role="listview" data-icon="false" id="menu">

            <li>
            <a href="#" id = "btnA" data-rel="close">Go Page A <img src="./images/icona.png" class="ui-li-thumb"/>
            </li>

        </ul>

    </div><!-- /panel -->


    <script type="text/javascript">

        $("#btnA").on("click", function(){  

            var listposts = window.jsinterface.getPostValue();
            document.getElementById( "maindiv" ).innerHTML = "<html><body>"+listposts+"</body></html>";
        });


    </script>

</div><!-- /page -->

</body>
</html> 

0 个答案:

没有答案