I am right now working on an app which works as a book-stack,where user can read books of their choice,now what i am doing is,displaying the html pages that i've made,in a web-view in my application.
Now this application works only if the user has full time internet connection on his phone.
What exactly i want is when they first open the application,they would need internet connection and then the app should be able to download that page and store it in local database so the user can read it later on without having any internet connect.
So is there any possible way to download the html page and store it in local database so user can use the app even if he is not connected to internet?
I can post my code here if needed be.
Any smallest tip or help would be really great as i am stuck here since long now:(
EDIT 1:
So i successfully downloaded the HTLM page from the website,but now the problem that i am facing is,that i cannot see any of the images of the downloaded html. What can be a proper solution for this?
Here what's the mean of "Local Database"?
Preferred way is download your pages in either Internal Storage(/<data/data/<application_package_name>) (by default on non rooted device is private to your application) or on External Storage(public access). Then refer the pages from that storage area when user device has not a internet connection (offline mode).
Update: 1
To store those pages, you can use simple File read/write operation in Android.
For example:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
This example store file hello_file in your application's internal storage directory.
Update: 2 Download Web-Content
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://www.xxxx.com");
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()
)
);
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
}
// Now you have the whole HTML loaded on the result variable
So write result variable in File, using my update 1 code. Simple.. :-)
Don't forget to add these two permission in your android application's manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Code snippet for downloading web page. Check the comments in the code. Just provide the link ie www.mytestpage.com/story1.htm as downloadlink to the function
void Download(String downloadlink,int choice)
{
try {
String USERAGENT;
if(choice==0)
{
USERAGENT ="Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_7; en-us) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Safari/530.17";
}
else
{
USERAGENT ="Mozilla/5.0 (Linux; U; Android 2.1-update1; en-us; ADR6300 Build/ERE27) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17";
}
URL url = new URL(downloadlink);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestProperty("User-Agent", USERAGENT); //if you are not sure of user agent just set choice=0
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
//set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
File dir = new File (SDCardRoot.getAbsolutePath() + "/yourfolder");
if(!dir.exists())
{
dir.mkdirs();
}
File file = new File(dir, "filename"); //any name abc.html
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
//close the output stream when done
fileOutput.close();
inputStream.close();
urlConnection.disconnect();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
I want to download all the images I have on server in the array string of Url one by one so that I may do not have to download a zip file of images from the server and to unzip after downloading it.
So I thought to download the images one by one and to show the download status in the progress bar. But I am extremely failed in it. An Idea came into my mind to make the string array of the Url and to use the For loop to download but it is downloading the last image of the String array and decline or pass all other images in the array . I think I have got the idea that what is going on but I have know Idea what would be the solution then.
What I have done So far
protected Void doInBackground(Void... arg0) {
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
String [] imageUrl = {"http://www.androidbegin.com/tutorial/flag/india.png","http://www.androidbegin.com/tutorial/flag/pakistan.png"
,"http://www.androidbegin.com/tutorial/flag/china.png","http://www.androidbegin.com/tutorial/flag/unitedstates.png"};
URL url;
HttpURLConnection urlConnection = null;
for(int i=0;i<imageUrl.length;i++){
url = new URL(imageUrl[i]);
//create the new connection
urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
}
File storagePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Test");
storagePath.mkdirs();
String finalName = Long.toString(System.currentTimeMillis());
File myImage = new File(storagePath, finalName + ".png");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(myImage);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ((bufferLength = inputStream.read(buffer)) > 0) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
// updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// see http://androidsnippets.com/download-an-http-file-to-sdcard-with-progress-notification
return null;
}
** What I want :**
Download all the images one by one.
After downloading one Image it should get save in the device and update the progress status.
Please show me some source code rather then giving me just Idea how to do it. And little source code and complete work around on this would be appreciated.
the saving image code should be taken inside for loop. as this code is outside of for loop only your last image is getting saved as at the end of for loop last url is used.
I'm downloading a PDF from my server.
The server send me a HttpResponse with the InputStream of file's body.
I'm able to write it into a file but, when I try to read it with a PDF reader, it tells me that the file might be corrupted.
I've also noticed that the size of the PDF downloaded directly from web service is twice the size of the PDF downloaded via my application.
The code I use to download and write the PDF file is this:
String fileName = //FILENAME + ".pdf";
fileName = fileName.replaceAll("/", "_");
String extPath = Environment.getExternalStorageDirectory().toString();
String folderName = //FOLDERNAME;
try {
File folder = new File(extPath, folderName);
folder.mkdir();
File pdfFile = new File(folder, fileName);
pdfFile.createNewFile();
URL url = new URL(downloadURL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(pdfFile);
byte[] buffer = new byte[MEGABYTE];
int bufferLength;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
//otherStuff
Where I go wrong?
I've also noticed that inside the Headers of HttpResponse contains Content-type:text/html. It shoudld be something like text/pdf?
Your Downloading code seems correct. Based on that and on your comment:
I've also noticed that the size of the PDF downloaded directly from web service is twice the size of the PDF downloaded via my application."
I would suggest checking your URL. It appears that you might be downloading an html page instead of the pdf. To verify you are downloading correctly, change the download directory as follows:
//Default download directory
String extPath = Environment.DIRECTORY_DOWNLOADS;
And check the directory (via the file system, e.g. mount the phone to your computer or a file manager app) for the downloaded content to verify it is a pdf.
I'm trying to use the following code to download and then eventually view a PDF file. The URL of the file is like this:
http://www.example.com/directory/something.example.com This File.pdf
I've tried replacing the spaces with %20, I've tried "UrlEncoder.encode", no matter what I get either FileNotFoundException or MalformedURLException (when encoding the URL). Example exceptions:
java.io.FileNotFoundException:
http://www.example.com/directory/something.example.com This File.pdf
java.io.FileNotFoundException:
http://www.example.com/directory/something.example.com%20This%20File.pdf
java.net.MalformedURLException: Protocol not found:
http%3A%2F%2Fwww.example.com%directory%2Fsomething.example.com+This+File.pdf
If I copy those paths into any browser it downloads fine.
File file;
try
{
String urlString =
"http://www.example.com/directory/something.example.com This File.pdf"
URL url = new URL(urlString);
//URL url = new URL(URLEncoder.encode(urlString, "UTF-8"));
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
file = new File(getExternalFilesDir(null), "test.pdf");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024 * 1024];
int bufferLength;
while ((bufferLength = inputStream.read(buffer)) > 0)
{
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.flush();
fileOutput.close();
inputStream.close();
return file.getAbsolutePath();
}
catch (Exception e)
{
Log.e(getClass().getSimpleName(), e.getMessage(), e);
return "";
}
The exception java.io.FileNotFoundException will be returned if the server responds with a 404 error code. Sometimes the error code and the data returned do not match. You can check for this (and get whatever data was returned) using the following:
boolean isError = urlConnection.getResponseCode() >= 400;
InputStream inputStream = = isError ? urlConnection.getErrorStream() : urlConnection.getInputStream();
And if you're connecting to a non-standard port, you can fix it by adding these headers to your request:
urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
urlConnection.setRequestProperty("Accept","*/*");
Your UrlEncoder attempts have been wrong. Here's the javadoc:
http://docs.oracle.com/javase/6/docs/api/java/net/URLEncoder.html
java.io.FileNotFoundException:
http://www.example.com/directory/something.example.com This File.pdf
Spaces were not encoded so it doesn't match your file.
java.io.FileNotFoundException:
http://www.example.com/directory/something.example.com%20This%20File.pdf
%20 are valid url symbols, so this also doesn't match your file.
java.net.MalformedURLException: Protocol not found:
http%3A%2F%2Fwww.example.com%directory%2Fsomething.example.com+This+File.pdf
Slash after .com is not encoded properly. Results in an incorrectly encoded url.
With UrlEncoder, you should be encoding the file name and concatenating it with the URL, not encoding the entire url string and use UTF-8 encoding. Anything else (not UTF-8) is not guaranteed to work.
If manually encoding spaces don't then pass them through the UrlEncoder.
hi developers i am developing a web based application in android. i want to download a webpage to sdcard to make loading of the webpage make faster. so i download the html file using the below code
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL("http://venusdigitalarcade.com/index.html");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"venus.html");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this maybe
// updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
this code only saves the html writings there is no designing part and css file and contents like images and videos
how can i download the full webpages with design and javascrpts and css?
You can create a file list for every resource you need or use a web crawler like http://code.google.com/p/crawler4j/
When i start downloading .apk on mobile handset(Google Nexus) from our site,following thing happens:
1.I get redirection link which is in the code
2.Start downloading the application but after download gets complete ,i get error download not completed(failed)
3. I get error page, saying page is not available,where as i an able to access net
here is the format of link to down load:/game.do?x=&y=&z=
Earlier i was able to download applications with same code.
.
If you have any idea about the problem please let me know.
Thanks
Rakesh
.apk size varies from 500KB to 5MB
Use below Code for download apk file from server
private void download(){
try {
URL url = new URL("url from apk file is to be downloaded");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "filename.ext");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And Refer below link for download and install apk file from url.
Download & Install APK File