I tried to create a class which downloads the HTML source from a link and saves it. I'm a newbie to all this Android stuff, even new to Java, but this is what I have so far.
It seems to work at least, although I cannot see the file since it is hidden.
package com.example.test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class PageDownloader {
String Filename;
String urlString;
Context context;
public PageDownloader( Context ctx) {
Filename = "tmpPage.html";
context = ctx;
}
public void download( String _url ){
urlString = _url;
testClass t = new testClass();
t.execute();
}
public void _download(){
/*
* First Download content
* Then Save File
*
*/
String result = null;
//DOWNLOAD
try {
URL url = new URL( urlString );
URLConnection con = url.openConnection();
con.connect();
InputStream in = con.getInputStream();
byte[] data = new byte[ in.available() ];
while( in.read(data) != -1 ){
result += new String(data);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//SAVE
saveFile( result );
}
private void saveFile( String r )
{
try {
File f = new File( context.getFilesDir(), "myfile" );
if( !f.exists() )
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);//context.openFileOutput(Filename, context.MODE_PRIVATE);
fos.write( r.getBytes() );
fos.close();
Log.w( "PageDownloader", "got it!" );
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
Log.w("PageDownloader", e.getMessage());
}
}
public class testClass extends AsyncTask<Void, Integer, Void>
{
@Override
protected Void doInBackground(Void... params) {
_download();
return null;
}
}
}
I call it from my onCreate method in my MainActivity.java :
PageDownloader p = new PageDownloader(this);
String url = "www.google.com/";
p.download( url );
How is this class written? Anything wrong or to improve?
I want to use this code to download several (maybe 5 up to 20) pages when I click on something. After I downloaded the source I want to extract information out of it. Maybe there is a way to make it faster.