从ViewPager中的缓存集加载webview数据

时间:2017-11-22 11:47:40

标签: android webview android-viewpager

我正在开发一个应用程序,我需要将webView设置为ViewPager的项目。我每次都使用创建newInstace()片段作为URL的arrayList的大小来做到这一点。 但是,我有超过20个要加载的URL,因此如果设置mPager.setOffscreenPageLimit(myArray.size())则需要太多负载。如果我使用mPager.setOffscreenPageLimit(1),那么它每次都会重新加载。那么,有没有办法阻止每次重新加载网页?

public static class PlaceholderFragment extends BaseFragment {

    Activity activity;
    private int media_position = 0;
    private String media_url = "";

    private static final String KEY_CONTENT = "CategoriesFragment:Content";
    private String mContent = "???";

    public static PlaceholderFragment newInstance(int media_position, String media_url) {

        PlaceholderFragment fragment = new PlaceholderFragment();
        fragment.media_position = media_position;
        fragment.media_url = media_url;
        return fragment;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(KEY_CONTENT, mContent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
            mContent = savedInstanceState.getString(KEY_CONTENT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        web1 = inflater.inflate(R.layout.fragment_main, container, false);
        activity = getActivity();

        mWebView1 = (WebView) web1.findViewById(R.id.webview);

        mWebView1.setWebViewClient(new WebViewClient());
        mWebView1.getSettings().setJavaScriptEnabled(true);
        mWebView1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView1.getSettings().setSupportMultipleWindows(true);
        mWebView1.getSettings().setSupportZoom(true);
        mWebView1.getSettings().setBuiltInZoomControls(false);
        mWebView1.getSettings().setAllowFileAccess(true);
        mWebView1.getSettings().setAppCacheEnabled(true);
        mWebView1.getSettings().setDomStorageEnabled(true);
        mWebView1.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

        mWebView1.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

                boolean isLoaded = false;

                if (Utils.LoadedUrlList.containsKey(Utils.currentUrl)) {
                    Log.e("Matched key", "media_position --> " + media_position + " currentUrl --> " + Utils.currentUrl);
                    isLoaded = true;
                } else {
                    Log.e("Not Matched", "media_position --> " + media_position + " media_url --> " + media_url);
                    isLoaded = false;
                }

                Log.e("onPageStarted", "onPageStarted");

                if (!isLoaded)
                    if (media_position == 0)
                        ShowProgressDialog(activity, activity.getString(R.string.loading));
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                Log.e("onPageFinished", "onPageFinished");
                Log.e("onPageFinished", "--> " + url);

                hideProgressDialog();
                CookieSyncManager.getInstance().sync();

                for (int i = 0; i < Utils.SocialURLList.size(); i++) {

                    if (url.equals(Utils.SocialURLList.get(i))) {
                        Utils.LoadedUrlList.put(Utils.SocialURLList.get(0), true);
                    }
                }
            }
        });

        mWebView1.loadUrl(media_url);
        return web1;
    }

}

2 个答案:

答案 0 :(得分:0)

webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

加载WebView并调用onPageFinished后,您可以将数据保存到cookie中。 同时添加<div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading"> Sila pilih kategori peperiksaan </div> <div class="panel-body"> <div class="row"> <div class="col-lg-6"> <form name="selection" role="form" method="post" action="index.php?pages=peperiksaan2" enctype="multipart/form-data" onsubmit="return validate_form ( );"> <div class="form-group"> <?php $sql = "SELECT tahun_nama FROM tahun"; $result = $con->query($sql); ?> <label for="tahun_nama">TAHUN</label> <select class="form-control" id="tahun_nama" name="tahun_id"> <option value=""<?php if(!isset($_POST['tahun_nama']) || (isset($_POST['tahun_nama']) && empty($_POST['tahun_nama']))) { ?>selected<?php } ?>>Sila pilih tahun</option> <?php while($row = $result->fetch_assoc()) { echo '<option value="'.$row['tahun_nama'].'"'. ((isset($_SESSION['tahun_nama']) && !empty($_SESSION['tahun_nama']) && ($_SESSION['tahun_nama'] == $row['tahun_nama'])) ? 'selected="selected"' : '') .'>'.$row['tahun_nama'].' </option>'; } ?> </select> </div> <div class="form-group"> <?php $sql = "SELECT peperiksaan_nama FROM peperiksaan"; $result = $con->query($sql); ?> <label>PEPERIKSAAN</label> <select class="form-control" id="peperiksaan_nama" name="peperiksaan_id"> <option value=""<?php if(!isset($_POST['peperiksaan_nama']) || (isset($_POST['peperiksaan_nama']) && empty($_POST['peperiksaan_nama']))) { ?>selected<?php } ?>>Sila pilih peperiksaan</option> <?php while($row = $result->fetch_assoc()) { ?> <option value="<?php echo $row['peperiksaan_nama']; ?>" <?php if(isset($_POST['peperiksaan_nama']) && $_POST['peperiksaan_nama'] == $row['peperiksaan_nama']) { ?>selected<?php } ?>><?php echo $row['peperiksaan_nama']; ?></option> <?php } ?> </select> </div> <div class="form-group"> <?php $sql = "SELECT darjah_nama FROM darjah"; $result = $con->query($sql); ?> <label>DARJAH</label> <select class="form-control" id="darjah_nama" name="darjah_id"> <option value=""<?php if(!isset($_POST['darjah_nama']) || (isset($_POST['darjah_nama']) && empty($_POST['darjah_nama']))) { ?>selected<?php } ?>>Sila pilih darjah</option> <?php while($row = $result->fetch_assoc()) { ?> <option value="<?php echo $row['darjah_nama']; ?>" <?php if(isset($_SESSION['darjah_nama']) && $_SESSION['darjah_nama'] == $row['darjah_nama']) { ?>selected<?php } ?>><?php echo $row['darjah_nama']; ?></option> <?php } ?> </select> </div> <div class="form-group"> <?php $result = mysqli_query($con,"SELECT * FROM kelas"); ?> <label>KELAS</label> <select class="form-control" id="kelas_nama" name="kelas_id"> <option value=""<?php if(!isset($_POST['kelas_nama']) || (isset($_POST['kelas_nama']) && empty($_POST['kelas_nama']))) { ?>selected<?php } ?>>Sila pilih kelas</option> <?php while($row = mysqli_fetch_array($result)) { echo " <option value=" . $row['kelas_nama'] . ">" . $row['kelas_nama'] ."</option>"; } ?> </select> </div> <!-- <button style="display: block; margin: 0 auto;" type="submit" name="select" class="btn btn-primary" href="pptt415.php">PAPAR</button--> <!--center><a class="btn btn-primary" href="index.php?pages=newpptt415" role="button">PAPAR</a></center--> <center><button type="submit" class="btn btn-primary">PAPAR</button></center> <!--a class="btn btn-primary" style="display: block; margin: 0 auto;" href="index.php?pages=edit_guru&guru_nama=?php echo $guru_nama ?>" role="button"><span class="glyphicon glyphicon-glyphicon glyphicon-pencil" aria-hidden="true"></span></a--> </form> </div> </div> </div> </div> </div>

答案 1 :(得分:0)

我必须做同样的事情。我发现保存onSaveInstanceState中的数据不能很好地扩展(我没有尝试@Ameer建议的cookie方法)。

相反,在下载HTML之后,您可以将HTML保存到这样的文件中:

    try {
        OutputStreamWriter outputStreamWriter =
                new OutputStreamWriter(context.openFileOutput(email_id + ".txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(email_body);
        outputStreamWriter.close();
    } catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }

并将email_id与当前时间保存在SharedPreferences

然后当片段再次加载时,检查email_id中是否存在SharedPreferences。如果没有,或者保存的时间超过了所需的缓存长度,则(重新)从Web加载页面。否则,请像这样调用缓存的email_body

public String getCachedHTML(String email_id) {
    String ret = "";
    try {
        InputStream inputStream = context.openFileInput(email_id + ".txt");

        ret = readFile(ret, inputStream);
    } catch (FileNotFoundException e) {
        Log.e("login activity", "Email cache not found: " + e.toString());
    } catch (IOException e) {
        Log.e("login activity", "Can not read email cache: " + e.toString());
    }
    return ret;
}`

您可以在webview上设置HTML,如下所示:

webView.loadData(email_body, "text/html; charset=UTF-8", null);