将网页保存到android中的webview缓存

时间:2015-03-05 12:16:07

标签: android android-webview

我正在创建一个应用程序,它将从互联网上下载一些网页,并在用户点击按钮时将其保存到缓存中,并在没有互联网可用时加载它们。当我运行我的代码时,我得到空指针异常。我在清单文件中添加了所有必要的权限。

public class MainActivity extends Activity {

Context context;
ArrayList<String> fileNames = new ArrayList<String>();
ArrayList<String> urls = new ArrayList<String>();
ArrayList<String> paths = new ArrayList<String>();
ArrayList<File> files = new ArrayList<File>();
boolean internet;

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

    Button saveSiteOne = (Button)findViewById(R.id.button1);
    saveSiteOne.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {

        urls.add("http://www.google.com"); 
        urls.add("http://www.facebook.com"); 

        for(int i=0;i<urls.size();i++){
            fileNames.add("file"+i+".html");
        }

        //Loop to get paths of files
        for(int i=0;i<urls.size();i++){
            paths.add(getApplicationContext().getFilesDir() + "/" + fileNames.get(i));
        }

        //Loop to create list of files getting from stored paths
        for(int i=0;i<urls.size();i++){
            files.add(new File(paths.get(i)));
        }

        internet = isNetworkAvailable();

        WebView webView = new WebView(context);
        WebSettings webSettings = webView.getSettings();
        webView.getSettings().setAppCacheMaxSize( 5 * 1024 * 1024 ); // 5MB
        webView.getSettings().setAppCachePath( context.getCacheDir().getAbsolutePath() );
        webView.getSettings().setAllowFileAccess( true );
        webView.getSettings().setAppCacheEnabled( true );
        webView.getSettings().setJavaScriptEnabled( true );
        webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT ); // load online by default

        new downloadContentOfPage().execute();


       }
   });
}


class downloadContentOfPage extends AsyncTask<String, Void, String> {

    FileOutputStream fos;
    String result = ""; 
    ProgressDialog progressDialog;
    int position;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        Log.e( "pre execute","yes"); 

        try {
            fos = context.openFileOutput(fileNames.get(position), Context.MODE_PRIVATE);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }   

    @Override
    protected String doInBackground(String... params) {

        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        //give your url of html page that you want to download first time.
        HttpGet httpGet = new HttpGet(urls.get(position));
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpGet, localContext);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()
                            )
                    );
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String line = null;
        try {
            while ((line = reader.readLine()) != null){
                result += line + "\n";
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }


    @Override
    protected void onPostExecute(String res) {

        try {
            fos.write(res.getBytes());
            fos.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Toast.makeText( context.getApplicationContext(),"saved", Toast.LENGTH_LONG).show();
        if(progressDialog.isShowing()) {
           progressDialog.dismiss();
        } 

    }
}

logcat的

03-05 17:07:08.269: E/AndroidRuntime(14974): FATAL EXCEPTION: main
03-05 17:07:08.269: E/AndroidRuntime(14974): java.lang.NullPointerException
03-05 17:07:08.269: E/AndroidRuntime(14974):    at android.view.ViewConfiguration.get(ViewConfiguration.java:318)
03-05 17:07:08.269: E/AndroidRuntime(14974):    at android.view.View.<init> (View.java:3254)
03-05 17:07:08.269: E/AndroidRuntime(14974):    at android.view.View.<init>(View.java:3299)
03-05 17:07:08.269: E/AndroidRuntime(14974):    at android.view.ViewGroup.<init>(ViewGroup.java:443)
 03-05 17:07:08.269: E/AndroidRuntime(14974):   at   android.widget.AbsoluteLayout.<init>(AbsoluteLayout.java:52)
 03-05 17:07:08.269: E/AndroidRuntime(14974):   at android.webkit.WebView.<init>(WebView.java:556)
  03-05 17:07:08.269: E/AndroidRuntime(14974):  at android.webkit.WebView.<init>(WebView.java:533)
  03-05 17:07:08.269: E/AndroidRuntime(14974):  at android.webkit.WebView.<init>(WebView.java:513)
 03-05 17:07:08.269: E/AndroidRuntime(14974):   at android.webkit.WebView.<init>(WebView.java:502)
 03-05 17:07:08.269: E/AndroidRuntime(14974):   at android.webkit.WebView.<init>(WebView.java:492)
 03-05 17:07:08.269: E/AndroidRuntime(14974):   at com.example.html.MainActivity$1.onClick(MainActivity.java:78)
 03-05 17:07:08.269: E/AndroidRuntime(14974):   at android.view.View.performClick(View.java:4222)
 03-05 17:07:08.269: E/AndroidRuntime(14974):   at android.view.View$PerformClick.run(View.java:17620)
 03-05 17:07:08.269: E/AndroidRuntime(14974):   at android.os.Handler.handleCallback(Handler.java:800)
 03-05 17:07:08.269: E/AndroidRuntime(14974):   at android.os.Handler.dispatchMessage(Handler.java:100)
 03-05 17:07:08.269: E/AndroidRuntime(14974):   at android.os.Looper.loop(Looper.java:194)
03-05 17:07:08.269: E/AndroidRuntime(14974):    at android.app.ActivityThread.main(ActivityThread.java:5370)
03-05 17:07:08.269: E/AndroidRuntime(14974):    at java.lang.reflect.Method.invokeNative(Native Method)
03-05 17:07:08.269: E/AndroidRuntime(14974):    at java.lang.reflect.Method.invoke(Method.java:525)

1 个答案:

答案 0 :(得分:1)

问题在于:

    WebView webView = new WebView(context);

它会在这里:

    webView.getSettings().setAppCachePath( context.getCacheDir().getAbsolutePath() );

在这里:

    try {
        fos = context.openFileOutput(fileNames.get(position), Context.MODE_PRIVATE);
    }

在这里:

  Toast.makeText(context, "saved", Toast.LENGTH_LONG).show();

看一看。您使用了context变量但从未初始化它。删除此可行,并将其替换为MainActivity.this。

如下所示:

   WebView webView = new WebView(MainActivity.this);

在这里:

    webView.getSettings().setAppCachePath( MainActivity.this.getCacheDir().getAbsolutePath() );

在这里:

    try {
        fos = MainActivity.this.openFileOutput(fileNames.get(position), Context.MODE_PRIVATE);
    }

在这里:

  Toast.makeText(MainActivity.this, "saved", Toast.LENGTH_LONG).show();