how to display that how much data we have downloaded - android

I anm new to android.I am making an application in which i want to display the size of file that is downloaded from server.
Is there any way to display that how much we have downloaded?
Plz
if anyone can help out.
Thanks

I hope you are storing the the data whcih you get from server in a file in any particular location. So create a file passinb the absolute path of the location. use length() method to get the file size.
In this way you can get how much data you have downloaded from server
File f = new File("absolutepath");
if(f.exists()){
f.length()
}
Thanks
Deepak

Hey there. You may use the code below or preferred in async task, where in onProgressUpdate method you may check the size from the input source variable.
URL u = new URL("http://www.java2s.com/binary.dat");
URLConnection uc = u.openConnection();
String contentType = uc.getContentType();
int contentLength = uc.getContentLength();
if (contentType.startsWith("text/") || contentLength == -1) {
throw new IOException("This is not a binary file.");
}
InputStream raw = uc.getInputStream();
InputStream in = new BufferedInputStream(raw);
byte[] data = new byte[contentLength];
int bytesRead = 0;
int offset = 0;
while (offset < contentLength) {
bytesRead = in.read(data, offset, data.length - offset);
if (bytesRead == -1)
break;
offset += bytesRead;
}
in.close();

Just go through the documentation below, which explains async task. In its progress update u can check size of input sorce file.
If you want to show this to UI then use progress dialog.
ProgressDialog

Related

How to resume the downloading where it left in asynctask android

For example I am downloading a file from server, in between the connectivity is lost at that point in time my download was 30%, after some time I got a connection .Now I want to start a downloading from 30%, not from 0%.How to achieve this asynctask android.
If any alternative is there please, let me know.???
You need to first figure out how many bytes you have actually downloaded. I suggest saving your file with an different name when it's being downloaded so you can can easily see if you have an unfinished download.
Check the status of you file first to see how much you have downloaded.
private long isIncomplete(){
File from = new File(dir,fileName+"-incomplete");
if(from.exists()){
Log.d("status","download is incomplete, filesize:" + from.length());
return from.length();
}
return 0;
}
Then when creating your http request you can tell the server from what point to serve you the file so that you can resume download.
long downloaded = isIncomplete();
urlConnection.setRequestProperty("Range", "bytes="+(downloaded)+"-");
See this class that I wrote a few years back for a complete implementation.
Update: I suggest you do not use the Shared Preferences for this. SSOT states that you get the info from only one source not more hence reading the progress from the downloaded file.
You can store the destination file path in sharedpreferences and you can do the following code.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();//Opening the url
File file=new File(DESTINATION_PATH);
if(file.exists()){ //check if file exists
downloaded = (int) file.length();
connection.setRequestProperty("Range", "bytes="+(file.length())+"-");
}
else{
connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
}
connection.setDoInput(true);
connection.setDoOutput(true);
pBar.setMax(connection.getContentLength());
in = new BufferedInputStream(connection.getInputStream());
fos=(downloaded==0)? new FileOutputStream(DESTINATION_PATH): new FileOutputStream(DESTINATION_PATH,true);
bout = new BufferedOutputStream(fos, 1024);
byte[] data = new byte[1024];
int x = 0;
while ((x = in.read(data, 0, 1024)) >= 0) {
bout.write(data, 0, x);
downloaded += x;
pBar.setProgress(downloaded);
}

How to download all images one by one and show progress status

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.

How can I set my android app background from a server?

I'm quite new to android programming and I have the following problem.
I want to be able to put an image om my server and then if I use my app it should use that image as a background.
From previous research I understand I cant save any files to the drawable file?
So is this even possible?
I am now this far:
URL url = new URL ("http://oranjelan.nl/oranjelan-bg.png");
InputStream input = url.openStream();
try {
String storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (storagePath + "/oranjelangb.png");
try {
byte[] buffer = new byte[1000000];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
But I get the following error
# String storagePath = Environment.getExternalStorageDirectory();
The compiller says cannot convert file to string.
It should be possible. Simple steps may include :-
1) Download image file from server, Store it to SDcard or assets folder.
links for step 1 >> link1 link2
2) Create a Bitmap from the file you downloaded.
3) Set that bitmap as a Background image.
You can pick steps and search on SO there should be lots of answers available.

Some download troubles in Android

I use below code to download file:
URL u = new URL(one.getSrcPath());
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.setReadTimeout(10000);
c.connect();
int lenghtOfFile = c.getContentLength();
FileOutputStream f = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/" + SavePath, FileName);
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
int finishbyte = 0;
long total = 0;
while((len1 = in.read(buffer)) > 0) {
total += len1; //total = total + len1
f.write(buffer, 0, len1);
finishbyte++;
}
f.close();
I have two problems:
First, why my download task download fail very high frequency?
Second, if I want my download task resume from break point.
I have get the finishbyte.
How can I modify?
finishbyte both does not represent any information (except the number of calls to the read method, but certainly not the size of the downloaded file), and is not relevant, since you have written to a file and can use the File.length() method to know how much you got so far.
To resume a download:
Open your file, check the size, request a range using the http header that is:
Range: <file.length()>-
(example, if you have downloaded 234 bytes:
Range: 234-
If the response code from the server is 206 Partial Content, you can append to your file, if it is 200, you have to overwrite your file (content have changed or Range is not supported)
To start downloading a file starting with finishbyte position, you will have to use the Range HTTP header. As for the failed downloads problem, it's probably a network issue or phone sleep issue, in which case you should check out the wifi lock

Android: Base64 Sample issue

currently I'm using kSoap to publish data to C# web services. Now I've come to the part where I need to upload images from my machine using Base64Binary. I searched everywehre internet but couldn't come up with a proper solution.
there is a solution with external Base64 class example but I'm interested in native solution as there is a API from Android 2.2.
Since I'm a newbie I couldn't do it myself. Basically I have a sd card file path of images, I want to convert them into Base64 format to upload.
Hope someone can help me or direct me to proper documents.
Thanks in advance.
Please try this, use Base64.java from link you have specified.
Bitmap bmImage = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + File.separator + "Your filename");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
String encodedString = Base64.encodeBytes( baos.toByteArray() );
You should change extension of this Bitmap.CompressFormat.JPEG statement according to your file type. You can decode a base 64 string to image using following code
byte[] b;
b = Base64.decode("base 64 string");
final Bitmap unscaledBitmap = BitmapFactory.decodeByteArray(b, 0, b.length );
I figured out the issue
String Image64 = null;
try {
Image64 = Base64.encodeToString((getBytesFromFile(new File(path))), DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
//encording
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}

Categories

Resources