网页保存到Android的web视图缓存 [英] save webpages to webview cache in android
问题描述
我创建一个应用程序将从网上下载一些网页,并将它们保存到缓存中,当一个按钮用户点击并加载它们后,当没有网络可用。当我运行我的code我得到空指针异常。我在清单文件中添加了所有必要的权限。
公共类MainActivity延伸活动{上下文语境;
ArrayList的<串GT;文件名=新的ArrayList<串GT;();
ArrayList的<串GT;网址=新的ArrayList<串GT;();
ArrayList的<串GT;路径=新的ArrayList<串GT;();
ArrayList的<文件>文件=新的ArrayList<文件>();
布尔网络;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.mainscreen); 按钮saveSiteOne =(按钮)findViewById(R.id.button1);
saveSiteOne.setOnClickListener(新View.OnClickListener(){
公共无效的onClick(视图v){ urls.add(http://www.google.com);
urls.add(http://www.facebook.com); 的for(int i = 0; I< urls.size();我++){
fileNames.add(文件+ I +HTML);
} //循环获取文件夹路径
的for(int i = 0; I< urls.size();我++){
paths.add(getApplicationContext()getFilesDir()+/+ fileNames.get(ⅰ));
} //循环创建从存储的路径获得的文件列表
的for(int i = 0; I< urls.size();我++){
files.add(新文件(paths.get(I)));
} 互联网= isNetworkAvailable(); web视图的WebView =新的WebView(背景);
WebSettings webSettings = webView.getSettings();
。webView.getSettings()setAppCacheMaxSize(5 * 1024 * 1024); // 5MB
webView.getSettings()setAppCachePath(context.getCacheDir()getAbsolutePath()。)。
。webView.getSettings()setAllowFileAccess(真);
webView.getSettings()setAppCacheEnabled(真)。
webView.getSettings()setJavaScriptEnabled(真)。
。webView.getSettings()setCacheMode(WebSettings.LOAD_DEFAULT); //默认情况下,在网上载 新downloadContentOfPage()执行();
}
});
}
类downloadContentOfPage扩展的AsyncTask<弦乐,太虚,字符串> { FileOutputStream中FOS;
字符串结果=;
ProgressDialog progressDialog;
INT位置; @覆盖
在preExecute保护无效(){
super.on preExecute(); progressDialog =新ProgressDialog(MainActivity.this);
progressDialog.setMessage(正在加载...);
progressDialog.setCancelable(假);
progressDialog.show();
Log.e(pre执行,是); 尝试{
FOS = context.openFileOutput(fileNames.get(位置),Context.MODE_PRIVATE);
}
赶上(IOException异常五){
e.printStackTrace();
}
} @覆盖
保护字符串doInBackground(字符串... PARAMS){ HttpClient的HttpClient的=新DefaultHttpClient();
HttpContext的localContext =新BasicHttpContext();
//给你的,你要下载的第一次HTML页面的URL。
HTTPGET HTTPGET =新HTTPGET(urls.get(位置));
HTT presponse响应= NULL;
尝试{
响应= httpClient.execute(HTTPGET,localContext);
}赶上(ClientProtocolException E){
e.printStackTrace();
}赶上(IOException异常五){
e.printStackTrace();
}
读者的BufferedReader = NULL;
尝试{
读者=新的BufferedReader(
新的InputStreamReader(response.getEntity()的getContent()
)
);
}赶上(IllegalStateException异常五){
// TODO自动生成catch块
e.printStackTrace();
}赶上(IOException异常五){
// TODO自动生成catch块
e.printStackTrace();
} 串线= NULL;
尝试{
而((行= reader.readLine())!= NULL){
结果+ =行+\\ n;
}
}赶上(IOException异常五){
// TODO自动生成catch块
e.printStackTrace();
}
返回结果;
}
@覆盖
保护无效onPostExecute(字符串RES){ 尝试{
fos.write(res.getBytes());
fos.close(); }赶上(IOException异常五){
// TODO自动生成catch块
e.printStackTrace();
} Toast.makeText(context.getApplicationContext(),拯救,Toast.LENGTH_LONG).show();
如果(progressDialog.isShowing()){
progressDialog.dismiss();
} }
}
logcat的
03-05 17:07:08.269:E / AndroidRuntime(14974):致命异常:主要
03-05 17:07:08.269:E / AndroidRuntime(14974):显示java.lang.NullPointerException
03-05 17:07:08.269:E / AndroidRuntime(14974):在android.view.ViewConfiguration.get(ViewConfiguration.java:318)
03-05 17:07:08.269:E / AndroidRuntime(14974):在android.view.View<&初始化GT; (View.java:3254)
。03-05 17:07:08.269:E / AndroidRuntime(14974):在android.view.View<&初始化GT;(View.java:3299)
。03-05 17:07:08.269:E / AndroidRuntime(14974):在android.view.ViewGroup<&初始化GT;(ViewGroup.java:443)
。03-05 17:07:08.269:E / AndroidRuntime(14974):在android.widget.AbsoluteLayout<&初始化GT;(AbsoluteLayout.java:52)
03-05 17:07:08.269:E / AndroidRuntime(14974):在android.webkit.WebView<&初始化GT;(WebView.java:556)
03-05 17:07:08.269:E / AndroidRuntime(14974):在android.webkit.WebView<&初始化GT;(WebView.java:533)
03-05 17:07:08.269:E / AndroidRuntime(14974):在android.webkit.WebView<&初始化GT;(WebView.java:513)
03-05 17:07:08.269:E / AndroidRuntime(14974):在android.webkit.WebView<&初始化GT;(WebView.java:502)
03-05 17:07:08.269:E / AndroidRuntime(14974):在android.webkit.WebView<&初始化GT;(WebView.java:492)
03-05 17:07:08.269:E / AndroidRuntime(14974):在com.example.html.MainActivity $ 1.onClick(MainActivity.java:78)
03-05 17:07:08.269:E / AndroidRuntime(14974):在android.view.View.performClick(View.java:4222)
03-05 17:07:08.269:E / AndroidRuntime(14974):在android.view.View $ PerformClick.run(View.java:17620)
03-05 17:07:08.269:E / AndroidRuntime(14974):在android.os.Handler.handleCallback(Handler.java:800)
03-05 17:07:08.269:E / AndroidRuntime(14974):在android.os.Handler.dispatchMessage(Handler.java:100)
03-05 17:07:08.269:E / AndroidRuntime(14974):在android.os.Looper.loop(Looper.java:194)
03-05 17:07:08.269:E / AndroidRuntime(14974):在android.app.ActivityThread.main(ActivityThread.java:5370)
03-05 17:07:08.269:E / AndroidRuntime(14974):在java.lang.reflect.Method.invokeNative(本机方法)
03-05 17:07:08.269:E / AndroidRuntime(14974):在java.lang.reflect.Method.invoke(Method.java:525)
该问题是在这里:
的WebView web视图=新的WebView(背景);
和这将是在这里:
webView.getSettings()setAppCachePath(context.getCacheDir()getAbsolutePath()。)。
在这里:
{尝试
FOS = context.openFileOutput(fileNames.get(位置),Context.MODE_PRIVATE);
}
在这里:
Toast.makeText(背景下,拯救,Toast.LENGTH_LONG).show();
看一看。你用背景
变量,但你永远不会初始化。删除此可行和MainActivity.this取代它。
如下面所示:
的WebView web视图=新的WebView(MainActivity.this);
在这里:
webView.getSettings()setAppCachePath(MainActivity.this.getCacheDir()getAbsolutePath()。)。
在这里:
{尝试
FOS = MainActivity.this.openFileOutput(fileNames.get(位置),Context.MODE_PRIVATE);
}
在这里:
Toast.makeText(MainActivity.this,拯救,Toast.LENGTH_LONG).show();
I'm creating an app which will download some webpages from internet and save them to cache when user clicks on a button and load them later when no internet is available. when I run my code I get null pointer exception. I have added all the necessary permissions in the manifest file.
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)
The problem is here:
WebView webView = new WebView(context);
and it will be here :
webView.getSettings().setAppCachePath( context.getCacheDir().getAbsolutePath() );
and here :
try {
fos = context.openFileOutput(fileNames.get(position), Context.MODE_PRIVATE);
}
and here:
Toast.makeText(context, "saved", Toast.LENGTH_LONG).show();
Take a look. You used context
variable but you never initialise it. Remove this viable and replace it by MainActivity.this.
As is shown below:
WebView webView = new WebView(MainActivity.this);
and here :
webView.getSettings().setAppCachePath( MainActivity.this.getCacheDir().getAbsolutePath() );
and here :
try {
fos = MainActivity.this.openFileOutput(fileNames.get(position), Context.MODE_PRIVATE);
}
and here:
Toast.makeText(MainActivity.this, "saved", Toast.LENGTH_LONG).show();
这篇关于网页保存到Android的web视图缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!