How to download all files from server to SD-card - android

I have several files uploaded to my server , now what i am trying to do is i want to download all files one by one and save it in to one folder.
So basically i was trying to do something like [this][1] but some how i am not able to achieve this so i think an alternate way to do it. So i am planning to download all audio file of particular folder of server to my SD-card folder and then i will give path of SD-card to list-view and play that audio.
So basically my question is how can i download all file from server folder to my SD-card folder.
I have below piece of code which is working fine for single file.
public class ServerFileList extends Activity {
Uri uri;
URL urlAudio;
ListView mListView;
ProgressDialog pDialog;
private MediaPlayer mp = new MediaPlayer();
private List<String> myList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.serverfilelist);
mListView = (ListView) findViewById(R.id.listAudio);
// new getAudiofromServer().execute();
new downloadAudio().execute();
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
playSong(urlAudio + myList.get(position));
}
});
}
public void updateProgress(int currentSize, int totalSize) {
TextView mTextView = new TextView(ServerFileList.this);
mTextView.setText(Long.toString((currentSize / totalSize) * 100) + "%");
}
private void playSong(String songPath) {
try {
mp.reset();
mp.setDataSource(songPath);
mp.prepare();
mp.start();
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
class downloadAudio extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ServerFileList.this);
pDialog.setMessage("Downloading File list from server, Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// set the download URL, a url that points to a file on the internet
// this is the file to be downloaded
URL url = null;
try {
url = new URL("http://server/folder/uploadAudio/abcd.mp3");
} catch (MalformedURLException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
// create the new connection
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e5) {
// TODO Auto-generated catch block
e5.printStackTrace();
}
// set up some things on the connection
try {
urlConnection.setRequestMethod("GET");
} catch (ProtocolException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
urlConnection.setDoOutput(true);
// and connect!
try {
urlConnection.connect();
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
// 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.
String MEDIA_PATH = new String(
Environment.getExternalStorageDirectory()
+ "/newDirectory/");
File SDCardRoot = new File(MEDIA_PATH);
if (!SDCardRoot.exists()) {
SDCardRoot.mkdir();
}
// create a new file, specifying the path, and the filename
// which we want to save the file as.
File file = new File(SDCardRoot, System.currentTimeMillis()
+ ".mp3");
// this will be used to write the downloaded data into the file we
// created
FileOutputStream fileOutput = null;
try {
fileOutput = new FileOutputStream(file);
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
// this will be used in reading the data from the internet
InputStream inputStream = null;
try {
inputStream = urlConnection.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 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
try {
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);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// close the output stream when done
try {
fileOutput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
// catch some possible errors...
}
protected void onPostExecute(String file_url) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
}
class getAudiofromServer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ServerFileList.this);
pDialog.setMessage("Getting File list from server, Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#SuppressWarnings("unchecked")
#Override
protected String doInBackground(String... arg0) {
try {
urlAudio = new URL("http://server/folder/uploadAudio");
} catch (MalformedURLException e) {
e.printStackTrace();
}
ApacheURLLister lister1 = new ApacheURLLister();
try {
myList = lister1.listAll(urlAudio);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
ServerFileList.this, android.R.layout.simple_list_item_1,
myList);
adapter.notifyDataSetChanged();
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mListView.setCacheColorHint(Color.TRANSPARENT);
}
}
}

Try follow steps,
Write a server side component which will return back the list of the files in the directory in which all the audio files are hosted.
In your downloadAudio class, instead of downloading a file, initially make a call to the component described above to get the list.
Move the code which you have written in an function which will take String argument.
Loop on the url list from step 2 and call function in step 3 with parameter as current element of url list.
Keep all checks and balances to ensure all the files are downloaded.
Your issue is more of design issue then programming.

I have solved the problem by adding ivy jar file as a library and then added following code.
try {
urlAudio = new URL("http://server/folder/uploadAudio");
} catch (MalformedURLException e) {
e.printStackTrace();
}
ApacheURLLister lister1 = new ApacheURLLister();
try {
myList = lister1.listAll(urlAudio);
} catch (IOException e) {
e.printStackTrace();
}
return null;

Related

Does base64 decoding disable search in pdf files?

There is Arabic encoded pdf file that is received from a server via a web service in my Android application, then I decode it and save it to be cashed to open it anytime,this is the file I download_which also is encoded_ the problem is the file became not searchable anymore, this is the code I use to decode the file:
protected Void doInBackground(String... myLink) {
if (conDetector.isConnectingToInternet()) {
File myDir = getFilesDir();
String fileName = PDFCACHE;
File cachedFile = new File(myDir, fileName);
// to check if the cached file in the memory or not
if (cachedFile.exists()) {
try {
readPDFFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (!cachedFile.exists()) {
try {
URL url = new URL(myLink[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
file_size = urlConnection.getContentLength();
source = new BufferedInputStream(url.openStream(), 8192);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
buffer = new byte[1024];
long total = 0;
int count = 0;
// buffer=new
// Scanner(source).useDelimiter("\\A").next().getBytes();*/
// buffer = Base64.decode(buffer, 0);
for (int i; (i = source.read(buffer)) != -1;) {
total += i;
bos.write(buffer, 0, i); // no doubt here is 0
publishProgress(""
+ (int) ((total * 100) / file_size));
}
if (flag == false) {
bytes = bos.toByteArray();
bytes = Base64.decode(bytes, Base64.DEFAULT);
String decodedString = new String(bytes);
if (bytes != null) {
openBuffer(bytes);
if (manipulateCache())
try {
savePDFFile(bytes);
// source.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
core = openFile(decodedString);
}
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// when there is no internet connection "offline mode"
} else if (!(conDetector.isConnectingToInternet())) {
if (!PDFCACHE.equals(null)) {
try {
readPDFFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
} }
The file you received is not searchable, the font objects contain ToUnicode maps claiming most of the glyphs used are numbers, symbols, or Latin characters which does not match their appearance as Arabic characters.
Thus, no standard PDF viewer can be used to search the files.

saving data to interal memory with async task (newboston tutorials sample) error it has progress bar

this is my first post here
i'm new, so be good with me!
i'm following travis's tutorials and it goes to saving data and using async task
i really focused but i can't find out whats wrong with my code, so i posted here! :
I added the logcat!
it worked without async and progress bar (both save and load)
latest changes!:
i fixed the progress bar but loadwithasync class is not working, i mean this line:
I think this must return the Srting ld and set that in text view res. but it is not looking this way! why travis from mybringback! didn't wrote the line like Strig s = new loadWith..... ? can u tell me where is the problem! i'm confused and i don't know how to debug properly!!
new loadWithAsyncTask().execute(FILENAME);
public class SaveAndLoadInternal extends Activity implements OnClickListener {
EditText file, data;
TextView res;
FileInputStream fis;
FileOutputStream fos;
String FILE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.save_load_internal);
Button load, save;
file = (EditText) findViewById(R.id.etSLIfile);
data = (EditText) findViewById(R.id.etSLIdata);
res = (TextView) findViewById(R.id.tvSLIres);
load = (Button) findViewById(R.id.bSLIload);
save = (Button) findViewById(R.id.bSLIsave);
// set file and close it!
load.setOnClickListener(this);
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
FILE_NAME = file.getText().toString();
switch (v.getId()) {
case R.id.bSLIload:
//Commented just for doing some tweaks! run
//loading process in another thread to give UI thread rest :D for avoid hanging!
FileInputStream fis = null;
String ld = "LOADING FAILED!";
/* try {
fis = openFileInput(FILE_NAME);
byte[] b = new byte[fis.available()];
while (fis.read(b) != -1) {
ld = new String(b);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
res.setText(ld);
*/
new loadWithAsyncTask ().execute(FILE_NAME);
// execute will run doInBackground method!
break;
case R.id.bSLIsave:
String sd = data.getText().toString();
/*
// one way to save in file is below! must work but it isn't!
File f = new File(FILE_NAME);
try {
fos = new FileOutputStream(FILE_NAME);
fos.write(sd.getBytes());
fos.close();
res.setText("SAVING DONE!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
*/
try {
fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
fos.write(sd.getBytes());
fos.close();
res.setText("SAVING DONE!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
// /*
// first param: what is being passed in (FILE_NAME)
// second param for progress bar (we use integer here)
// third one is what we will return! (the saved text! String ld)
public class loadWithAsyncTask extends AsyncTask<String, Integer, String>{
ProgressDialog pd;
String Ld = "LOADING FAILED!";
FileInputStream fis = null;
// this gonna called first
#Override
protected void onPreExecute(){
// example: setting up variables or something else!
pd = new ProgressDialog(SaveAndLoadInternal.this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMax(100);
pd.show();
}
#Override
protected String doInBackground(String... params) {
//for progress dialog
for(int i =0 ; i< 20 ; i++){
publishProgress(5);
try {
Thread.sleep(88);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
pd.dismiss();
try {
fis = openFileInput(FILE_NAME);
byte[] b = new byte[fis.available()];
res.setText(String.valueOf(fis.available()));
while (fis.read(b) != -1) {
Ld = new String(b);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
//return the string!
return Ld;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
// progress of loading in example!
#Override
protected void onProgressUpdate(Integer...progress){
pd.incrementProgressBy(progress[0]);
}
}// */
}
When you look at the error, you'll see that onProgressUpdate() throws a NPE. Looking at the code, there are two possibilities: 1. pd is null or 2. progress is null. Add a breakpoint or some logging there to see what exactly is going on.
protected void onProgressUpdate(Integer...progress){
pd.incrementProgressBy(progress[0]);
}

Concatenate two audio files and play resulting file

I am really facing problem from last couple of days but I am not able to find the exact solution please help me.
I want to merge two .mp3 or any audio file and play final single one mp3 file. But when I am combine two file the final file size is ok but when I am trying to play it just play first file, I have tried this with SequenceInputStream or byte array but I am not able to get exact result please help me.
My code is the following:
public class MerginFileHere extends Activity {
public ArrayList<String> audNames;
byte fileContent[];
byte fileContent1[];
FileInputStream ins,ins1;
FileOutputStream fos = null;
String combined_file_stored_path = Environment
.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/final.mp3";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audNames = new ArrayList<String>();
String file1 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/one.mp3";
String file2 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/two.mp3";
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/AudioRecorder/" + "final.mp3");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
audNames.add(file1);
audNames.add(file2);
Button btn = (Button) findViewById(R.id.clickme);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
createCombineRecFile();
}
});
}
public void createCombineRecFile() {
// String combined_file_stored_path = // File path in String to store
// recorded audio
try {
fos = new FileOutputStream(combined_file_stored_path, true);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
File f = new File(audNames.get(0));
File f1 = new File(audNames.get(1));
Log.i("Record Message", "File Length=========>>>" + f.length()+"------------->"+f1.length());
fileContent = new byte[(int) f.length()];
ins = new FileInputStream(audNames.get(0));
int r = ins.read(fileContent);// Reads the file content as byte
fileContent1 = new byte[(int) f1.length()];
ins1 = new FileInputStream(audNames.get(1));
int r1 = ins1.read(fileContent1);// Reads the file content as byte
// from the list.
Log.i("Record Message", "Number Of Bytes Readed=====>>>" + r);
//fos.write(fileContent1);// Write the byte into the combine file.
byte[] combined = new byte[fileContent.length + fileContent1.length];
for (int i = 0; i < combined.length; ++i)
{
combined[i] = i < fileContent.length ? fileContent[i] : fileContent1[i - fileContent.length];
}
fos.write(combined);
//fos.write(fileContent1);*
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
Log.v("Record Message", "===== Combine File Closed =====");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I already published an app with this function... try my method using SequenceInputStream, in my app I just merge 17 MP3 files in one and play it using the JNI Library MPG123, but I tested the file using MediaPlayer without problems.
This code isn't the best, but it works...
private void mergeSongs(File mergedFile,File...mp3Files){
FileInputStream fisToFinal = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mergedFile);
fisToFinal = new FileInputStream(mergedFile);
for(File mp3File:mp3Files){
if(!mp3File.exists())
continue;
FileInputStream fisSong = new FileInputStream(mp3File);
SequenceInputStream sis = new SequenceInputStream(fisToFinal, fisSong);
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fisSong.read(buf)) != -1;)
fos.write(buf, 0, readNum);
} finally {
if(fisSong!=null){
fisSong.close();
}
if(sis!=null){
sis.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fos!=null){
fos.flush();
fos.close();
}
if(fisToFinal!=null){
fisToFinal.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Mp3 files are some frames.
You can concatenate these files by appending the streams to each other if and only if the bit rate and sample rate of your files are same.
If not, the first file plays because it has truly true encoding but the second file can not decode to an true mp3 file.
Suggestion: convert your files with some specific bit rate and sample rate, then use your function.

Download files in android

I am trying to write an application that downloads files in the background. The code crashes when it tries to reenter doInBackground(). This happens when doing is set to false before returning. Code follows -
public class DownloadFile extends AsyncTask<String, Integer, String> {
private boolean doing;
private Activity activity;
private Intent intent;
private File beta;
private File alpha;
public DownloadFile(Activity act, Intent intent) {
this.activity = act;
this.intent = intent;
doing = false;
}
#Override
protected String doInBackground(String... sUrl) {
int fileCount = 0;
if (!download(sUrl[0] + "list.txt",
Environment.getExternalStorageDirectory() + "/alpha/list.txt")){
setDoing(false);
return "Download failed";//list.txt could not be downloaded. return error message.
}
fileCount++;
beta = new File(Environment.getExternalStorageDirectory() + "/beta/");
File betalist = new File(beta + "/list.txt");
alpha = new File(Environment.getExternalStorageDirectory() + "/alpha/");
File alphalist = new File(alpha + "/list.txt");
//verify that the file is changed.
if (alphalist.lastModified() == betalist.lastModified()// these two are
// never equal.
|| alphalist.length() == betalist.length()) { // better to check
// the length of
// the files.
setDoing(false);
return "Nothing to download.";
}
try {
FileReader inAlpha = new FileReader(alphalist);
BufferedReader br = new BufferedReader(inAlpha);
String s;
// read the name of each file in a loop
while ((s = br.readLine()) != null) {
// if(fileExistsInBeta(s)){
// copyFromBetaToAlpha(s);
// continue;
// }
// download the file.
//Url will truncate the trailing / so keep if statement as is.
if (!download(sUrl[0] + s,
Environment.getExternalStorageDirectory() + "/alpha/"
+ s)){
setDoing(false);
return "Failed at " + s;// the given file could not be downloaded. return error.
}
fileCount++;
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e("Pankaj", e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Pankaj", e.getMessage());
} catch (Exception e) {
Log.e("Pankaj", e.getMessage());
}
Log.d("Pankaj", "Download Done");
activity.overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
activity.finish();
Log.d("Pankaj", "MainActivity Killed");
// rename alpha to beta
deleteSubFolders(beta.toString());
beta.delete();
alpha.renameTo(beta);
if (!alpha.exists()) {
alpha.mkdir();
}
File upper = new File(alpha + "/upper/");
if (!upper.exists())
upper.mkdirs();
File lower = new File(alpha + "/lower/");
if (!lower.exists())
lower.mkdirs();
// ConfLoader.getInstance().reload();//to refresh the settings
// restart the activity
activity.overridePendingTransition(0, 0);
activity.startActivity(intent);
Log.d("Pankaj", "MainActivity restarted");
// now reset done status so we can start again.
setDoing(false);
return "Download finished.";// return the status for onPostExecute.
}
private void copyFromBetaToAlpha(String fileName) {
File beta=new File(Environment.getExternalStorageDirectory()+"/beta/"+fileName);
File alpha=new File(Environment.getExternalStorageDirectory()+"/alpha/"+fileName);
try {
FileInputStream fis=new FileInputStream(beta);
FileOutputStream fos=new FileOutputStream(alpha);
byte[] buf=new byte[1024];
int len;
while((len=fis.read(buf))>0){
fos.write(buf, 0, len);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
public boolean download(String url, String file) {
boolean successful = true;
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
conn.connect();
int filelen = conn.getContentLength();
File f = new File(file);
// skip download if lengths are same
// because the file has been downed fully.
if (f.exists() && filelen == f.length()) {
return successful;
}
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
FileOutputStream fos = new FileOutputStream(f);
while ((length = dis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fos.close();
buffer = null;
dis.close();
} catch (MalformedURLException mue) {
Log.e("SYNC getUpdate", "malformed url error", mue);
successful = false;
} catch (IOException ioe) {
Log.e("SYNC getUpdate", "io error", ioe);
successful = false;
} catch (SecurityException se) {
Log.e("SYNC getUpdate", "security error", se);
successful = false;
}
return successful;
}
private void deleteSubFolders(String uri) {
File currentFolder = new File(uri);
File files[] = currentFolder.listFiles();
if (files == null) {
return;
}
for (File f : files) {
if (f.isDirectory()) {
deleteSubFolders(f.toString());
}
// no else, or you'll never get rid of this folder!
f.delete();
}
}
public static int getFilesCount(File file) {
File[] files = file.listFiles();
int count = 0;
for (File f : files)
if (f.isDirectory())
count += getFilesCount(f);
else
count++;
return count;
}
public boolean isDoing() {
return doing;
}
/**
* #param doing
*/
public void setDoing(boolean doing) {
this.doing = doing;
}
private boolean fileExistsInBeta(final String fileName){
boolean exists=false;
File beta=new File(Environment.getExternalStorageDirectory()+"/beta/"+fileName);
if(beta.exists()){
String[] ext=beta.getName().split(".");
String extName=ext[ext.length-1];
exists=(extName!="txt" && extName!="tmr" && extName!="conf");
}
return exists;
}
in the main activity -
public void run() {
if (!downloadFile.isDoing()) {
downloadFile.execute(ConfLoader.getInstance().getListUrl());
downloadFile.setDoing(true);
}
// change the delay so that it covers the time for download and
// doesn't overlap causing multiple downloads jamming the bandwidth.
h.postDelayed(this, 1000);//check after 60 sec.
}
in the onCreate() -
downloadFile = new DownloadFile(this, getIntent());
h = new Handler();
h.postDelayed(this, 1000);
Any help is appreciated. Thanks in advance.
EDIT:
The logcat error is Cannot execute task the task is already running.
Cannot execute task: Task has already been executed(A task can only be executed once).
EDIT:
Is it possible that the error is because I am trying to execute the asynchtask again in run(). Perhaps AsynchTask does not allow re-entry.
Try using this
1. First create a dialogue
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
The download async task
class DownloadFileAsync extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
File root = android.os.Environment.getExternalStorageDirectory();
//
File dir = new File (root.getAbsolutePath()+"/Downl");
if(dir.exists()==false) {
dir.mkdirs();
}
File file = new File(dir, url.substring(url.lastIndexOf("/")+1)); //name of file
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1)
{
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
Toast.makeText(DisplayActivity.this,"Successfully downloaded in phone memory.", Toast.LENGTH_SHORT).show();
}
}
Call the async new DownloadFileAsync().execute(url); //pass ur url

Android pause and resume downloading file to sdcard

I am making an application in which I need to download a file from server and save it to sd card of android device.
Apart of this there is a feature for the user to pause and resume the file.
The problem I am facing is that I am able to download file to sdcard but when try to pause and resume it, it gets starts from the beginning.......
Here is the source ......
public class DownloadWithProgressActivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn, pauseButton, resumeButton;
private ProgressBar bar;
URLConnection conexion;
OutputStream output;
static int count = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startBtn = (Button) findViewById(R.id.startBtn);
pauseButton = (Button) findViewById(R.id.button1);
resumeButton = (Button) findViewById(R.id.button2);
bar = (ProgressBar) findViewById(R.id.progressBar1);
bar.setVisibility(ProgressBar.INVISIBLE);
bar.setId(0);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
pauseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
resumeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// not getting what to write here
}
});
}
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
bar.setVisibility(ProgressBar.VISIBLE);
}
#Override
protected String doInBackground(String... aurl) {
int downloaded = 0;
File file = new File("/sdcard/some_photo_from_gdansk_poland.jpg");
URL url = null;
try {
url = new URL(aurl[0]);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
conexion = url.openConnection();
if (file.exists()) {
downloaded = (int) file.length();
conexion.setRequestProperty("Range", "bytes="+(file.length())+"-");
}
else {
conexion.setRequestProperty("Range", "bytes=" + downloaded
+ "-");
}
} catch (Exception exception1) {
}
conexion.setDoInput(true);
conexion.setDoOutput(true);
System.out.println(tryGetFileSize(url));
conexion.setRequestProperty("Range", "bytes=" + count + "-");
try {
conexion.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = null;
try {
input = new BufferedInputStream(url.openStream());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
output = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte data[] = new byte[1024];
long total = 0;
try {
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
bar.setProgress(Integer.parseInt(progress[0]));
System.out.println(Integer.parseInt(progress[0]));
}
protected void onPostExecute(String unused) {
}
int tryGetFileSize(URL url) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("HEAD");
conn.getInputStream();
return conn.getContentLength();
} catch (IOException e) {
return -1;
} finally {
conn.disconnect();
}
}
}
}
Please help.......
Thanks
Nikhil
connection.setRequestProperty("Range", "bytes=" + ***downloaded*** + "-");
Make "downloaded" as global variable, because download start from this position.
when you press on restart button, check value of this downloaded variable,must not zero all time.
This line return a wrong file size, I used the same code to open a Zip file on the net :
int lenghtOfFile = conexion.getContentLength();
How can I pause download other than by closing the output?
pauseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
resumeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// not getting what to write here
}
});

Categories

Resources