将网页保存到 android 中的 webview 缓存
save webpages to webview cache in android
我正在创建一个应用程序,它将从互联网上下载一些网页,并在用户单击按钮时将它们保存到缓存中,并在没有互联网可用时稍后加载它们。当我 运行 我的代码出现空指针异常时。我已经在清单文件中添加了所有必要的权限。
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.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)
问题出在这里:
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();
我正在创建一个应用程序,它将从互联网上下载一些网页,并在用户单击按钮时将它们保存到缓存中,并在没有互联网可用时稍后加载它们。当我 运行 我的代码出现空指针异常时。我已经在清单文件中添加了所有必要的权限。
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.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)
问题出在这里:
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();