how to download All File from Arraylist in android? - android

i want to all download video and save in sdcard.i have arraylist in all file.not a single file.how to possible it .please help me.
ArrayList<Url_Dto> list = new ArrayList<Url_Dto>();
Thanks in advance!!!
what is pass param in DownloadFileFromURL().i used button click event.
mainDownloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//what is pass param
new DownloadFileFromURL().execute();
}
});
may download class in below ::
class DownloadFileFromURL extends AsyncTask<Object, String, String> {
int count = 0;
ProgressDialog dialog;
ProgressBar progressBar;
int myProgress;
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressBar progressBar;
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(Object... params) {
Log.v("log_tag", "params :::; " + params);
int count;
progressBar = (ProgressBar) params[0];
try {
// URL url = new URL(f_url[0]);
URL url = new URL((String) params[1]);
Log.v("log_tag", "name ::: " + url);
name = ((String) params[1]).substring(((String) params[1])
.lastIndexOf("/") + 1);
Log.v("log_tag", "name Substring ::: " + name);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
download = new File(Environment.getExternalStorageDirectory()
+ "/download/");
if (!download.exists()) {
download.mkdir();
}
String strDownloaDuRL = download + "/" + name;
Log.v("log_tag", " down url " + strDownloaDuRL);
FileOutputStream output = new FileOutputStream(strDownloaDuRL);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
// publishProgress("" + (int) ((total * 100) /
// lenghtOfFile));
// writing data to file
progressBar
.setProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.v("log_tag", "progress :: " + values);
// setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
Log.v("log", "login ::: 4::: " + download);
String videoPath = download + "/" + name;
String chpName = name;
Log.v("log_tag", "chpName ::::" + chpName + " videoPath "
+ videoPath);
db.execSQL("insert into videoStatus (chapterNo,videoPath) values(\""
+ chpName + "\",\"" + videoPath + "\" )");
}
}

This link provides an idea on http file download. With that idea, you can iterate through all the video URLs in the list.

Related

Show File Download Progress in MB

I'm downloading a mp3 file from the internet and saving it into the internal storage. The progress of the download is shown in a ProgressDialog. The ProgressDialog displays the progress in percent which is fine. In the right it displays the progress as 1/100 .... I'd like it to display the current size of the file downloaded in MB / the total size of the file being downloaded in MB.
Like in the following picture. The grey text is the current text being displayed. I'd like it to be displayed like the text below it in red.
Here's the current code :
public class DownloadSKHindi extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Downloading");
progressDialog.setMax(100);
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
int count = 0;
try {
url = new URL(skURL[10]);
connection = url.openConnection();
connection.connect();
int lengthOfFile = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = getActivity().openFileOutput(file.getPath(), Context.MODE_PRIVATE);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / lengthOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
}
}
Assuming total is how many bytes are downloaded, and lengthOfFile is the size in bytes of how large the file is. You can do this:
progressDialog.setProgressNumberFormat((bytes2String(total)) + "/" + (bytes2String(lengthOfFile)));
Then using the function bytes2String ( Credit to coder )
private static double SPACE_KB = 1024;
private static double SPACE_MB = 1024 * SPACE_KB;
private static double SPACE_GB = 1024 * SPACE_MB;
private static double SPACE_TB = 1024 * SPACE_GB;
public static String bytes2String(long sizeInBytes) {
NumberFormat nf = new DecimalFormat();
nf.setMaximumFractionDigits(2);
try {
if ( sizeInBytes < SPACE_KB ) {
return nf.format(sizeInBytes) + " Byte(s)";
} else if ( sizeInBytes < SPACE_MB ) {
return nf.format(sizeInBytes/SPACE_KB) + " KB";
} else if ( sizeInBytes < SPACE_GB ) {
return nf.format(sizeInBytes/SPACE_MB) + " MB";
} else if ( sizeInBytes < SPACE_TB ) {
return nf.format(sizeInBytes/SPACE_GB) + " GB";
} else {
return nf.format(sizeInBytes/SPACE_TB) + " TB";
}
} catch (Exception e) {
return sizeInBytes + " Byte(s)";
}
}
Source
Use TextView that is appended after progressDialog inside XML file.
Consider TextView tv = findViewById();
Use this: publishProgress((int) (total * 100 / lengthOfFile), total ,lengthOfFile); to push new data.
And to update the tv use this:
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setProgress(values[0]);
tv.setText((values[1]/(1024*1024)) + "" +(values[1]/(1024*1024)));
}

How can i cancel running download file?

I want to cancel currently download file from notification area & I want to add cancel button at the bottom of notification download progress. By clicking on that cancel button, download should be cancel. Here is my class DownloadSong using which I perform download file. What modifications I need to do?
public class DownloadSong extends AsyncTask<String, Integer, String> {
Activity activity;
public static String songName, songURL;
private NotificationHelper mNotificationHelper;
public static int notificationID = 1;
boolean download = false;
NotificationManager nm;
public DownloadSong(Activity activity, String songName, String songURL) {
this.activity = activity;
this.songName = songName;
this.songURL = songURL;
mNotificationHelper = new NotificationHelper(activity, songName);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
notificationID++;
mNotificationHelper.createNotification(notificationID);
}
#Override
protected String doInBackground(String... file_URL) {
try {
URL url = new URL(songURL);
HttpURLConnection URLconnection = (HttpURLConnection) url.openConnection();
URLconnection.setRequestMethod("GET");
URLconnection.setDoOutput(true);
URLconnection.connect();
// Detect the file length
int fileLength = URLconnection.getContentLength();
File fSDcard = Environment.getExternalStorageDirectory();
String strSdcardPath = fSDcard.getAbsolutePath();
File fDirectory = new File(strSdcardPath + "/GSD");
if (!fDirectory.exists()) {
fDirectory.mkdir();
}
File fMyFile = new File(fDirectory.getAbsolutePath() + "/" + songName + ".mp3");
Log.e("Download file name ", fMyFile.toString());
FileOutputStream out = new FileOutputStream(fMyFile, true);
InputStream input_File = URLconnection.getInputStream();
byte[] data = new byte[1024];
int total = 0;
int count;
while ((count = input_File.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
out.write(data, 0, count);
}
out.flush();
out.close();
input_File.close();
} catch (IOException e) {
Log.e("Download Error : ", "Failed");
}
Log.e("Download status", " Complete ");
return null;
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(activity, "Song " + "'" + songName + "'" + " downloaded successfully", Toast.LENGTH_LONG).show();
//pDialog.dismiss();
if (download) {
Toast.makeText(activity, "Could Not Connect to Server.", Toast.LENGTH_LONG).show();
mNotificationHelper.clearNotification();
} else
mNotificationHelper.completed();
}
#Override
protected void onProgressUpdate(Integer... progress) {
//pDialog.setProgress(progress[0]);
mNotificationHelper.progressUpdate(progress[0]);
super.onProgressUpdate(progress);
}
}
Most of the time is spent in the loop
while ((count = input_File.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
out.write(data, 0, count);
}
You can add a check to see if the task is cancelled,
while ((count = input_File.read(data)) != -1 && !isCancelled()) {
total += count;
publishProgress((int) (total * 100 / fileLength));
out.write(data, 0, count);
}
and cancel the download by calling
yourAsyncTask.cancel()
You can cancel asynctask forcefully
Check This
declare your asyncTask in your activity:
private YourAsyncTask mTask;
instantiate it like this:
mTask = new YourAsyncTask().execute();
kill/cancel it like this:
mTask.cancel(true);

Android AsyncTask publishProgress not updating Dialog

I am trying to update a Progress Dialog to increment something like 1-100%. However, nothing ever increments. It always just says 0. Although, I am able to see the numbers print out in my Log Cat and everything ends when it should after 100.
Does anyone see what I am missing? Thanks in advance for any assistance.
private class DownLoadSigTask extends AsyncTask<String, Integer, String> {
private final ProgressDialog dialog = new ProgressDialog(NasStorageNasList.this);
// Set the fileName and filesize to be used later
String fileName = (String) recordItem.get(mPresentDown).get("name");
String filesize = (String) recordItem.get(mPresentDown).get("filesize");
// can use UI thread here
#Override
protected void onPreExecute() {
this.dialog.setMessage("Downloading " + fileName + " from the server. Please wait.");
this.dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.dialog.setCancelable(false);
this.dialog.setCanceledOnTouchOutside(false);
this.dialog.show();
}
// automatically done on worker thread (separate from UI thread)
#Override
protected String doInBackground(final String... args) {
// Here is where we need to do the downloading of the
try {
File destDir = new File(LOCALDOWNROOT);
if (!destDir.exists()) {
destDir.mkdirs();
}
File outputFile = new File(destDir, fileName);
Log.e("What is the filename path to download? ", REMOTEDOWNROOT + DATADIRECTORY + fileName);
InputStream fis = sardine.get(REMOTEDOWNROOT + DATADIRECTORY + "/"
+ fileName.replace(" ", "%20"));
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] buffer = new byte[1444];
Log.e("What is the length of the File Size? ", filesize);
long total = 0;
int byteread = 0;
while ((byteread = fis.read(buffer)) != -1) {
downloadTotal += byteread;
// Here is the WHILE LOOP that we will want to give the user
publishProgress((int)(total*100/Long.parseLong(filesize)));
Log.e("CurrentAmount Downloaded: ", String.valueOf((int)(downloadTotal*100/Long.parseLong(filesize))));
// How can I tell the UI the downloaded percentage?
// So, far I am updating the log cat...but nothing for the user.
fos.write(buffer, 0, byteread);
}
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
// Just Return null because the void task
return null;
}
// add in a progress bar update
#Override
protected void onProgressUpdate(Integer...progress) {
this.dialog.setProgress(progress[0]);
}
// can use UI thread here
#Override
protected void onPostExecute(final String errMsg) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
Toast.makeText(NasStorageNasList.this, "File Download Done!",
Toast.LENGTH_SHORT).show();
}
}// end DownloadSigTask
You have "typo" mistake. You need to replace in your publishProgress() method total variable with downloadTotal.
publishProgress((int) (downloadTotal * 100 / Long.parseLong(filesize)));
Your total variable is only assigned to zero before loop and is never changed to other value. So you performed division 0 / filesize that will be always 0.

how to all file download in android and save all file in sd card?

In my case i click download button when download all file but in show all file sdcard and some file display . and i used thread .what me wrong in my code : and Cancel(cl) button working but in i used delted download file is not working and {cl and dl button} setVisibitly not changed. My Code Below: Please Helpme>
mainDownloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adtf.setAllDownload();
}
});
}
public class MyListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
ProgressBar pr;
ProgressBar[] prArray = new ProgressBar[list.size()];
Button cl, dl;
ImageView im;
DownloadFileFromURL downloadFileFromURL;
public MyListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void setAllDownload() {
if (prArray.length > 0) {
for (int i = 0; i < prArray.length; i++) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
downloadFileFromURL.execute(pr, list.get(i).url_video, i);
}
}
}
public View getView(final int position, View convertView,
ViewGroup parent) {
convertView = mInflater.inflate(R.layout.custome_list_view, null);
cl = (Button) convertView.findViewById(R.id.cancle_sedual);
dl = (Button) convertView.findViewById(R.id.download_sedual);
pr = (ProgressBar) convertView.findViewById(R.id.listprogressbar);
prArray[position] = pr;
im = (ImageView) convertView.findViewById(R.id.list_image);
im.setImageResource(list.get(position).images[position]);
getProgress(pr, position, cl, dl);
// pr.setProgress(getItem(position));
cl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag","Cancle Button Click");
// dl.setVisibility(View.VISIBLE);
dl.setVisibility(View.VISIBLE);
cl.setVisibility(View.GONE);
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
//downloadFileFromURL.cancel(true);
downloadFileFromURL.downloadFile();
pr.setProgress(0);
}
});
dl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
str_start = list.get(position).url_video;
dl.setVisibility(View.GONE);
cl.setVisibility(View.VISIBLE);
Log.v("log_tag","Start Button Click ");
//
// new DownloadFileFromURL().execute(str_start);
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
downloadFileFromURL.execute(pr, str_start, position);
}
});
return convertView;
}
}
class DownloadFileFromURL extends AsyncTask<Object, String, Integer> {
int count = 0;
ProgressDialog dialog;
ProgressBar progressBar;
int myProgress;
int position;
Button start, cancel;
boolean download1 = false;
public DownloadFileFromURL(Button start, Button cancel) {
this.start = start;
this.cancel = cancel;
}
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressBar progressBar;
download1 = true;
}
public void downloadFile() {
this.download1 = false;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
/**
* Downloading file in background thread
* */
#Override
protected Integer doInBackground(Object... params) {
//Log.v("log_tag", "params :::; " + params);
int count;
progressBar = (ProgressBar) params[0];
position = (Integer) params[2];
try {
// URL url = new URL(f_url[0]);
URL url = new URL((String) params[1]);
//Log.v("log_tag", "name ::: " + url);
name = ((String) params[1]).substring(((String) params[1])
.lastIndexOf("/") + 1);
//Log.v("log_tag", "name Substring ::: " + name);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
download = new File(Environment.getExternalStorageDirectory()
+ "/download/");
if (!download.exists()) {
download.mkdir();
}
String strDownloaDuRL = download + "/" + name;
Log.v("log_tag", " down url " + strDownloaDuRL);
FileOutputStream output = new FileOutputStream(strDownloaDuRL);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
if (this.download1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
// publishProgress("" + (int) ((total * 100) /
// lenghtOfFile));
// writing data to file
progressBar
.setProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
setProgress(progressBar, position, start, cancel, this);
}
}
// flushing output
output.flush();
if(!this.download1){
File delete = new File(strDownloaDuRL);
delete.delete();
}
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return 0;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
// Log.v("log_tag", "progress :: " + values);
// setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
Log.v("log", "login ::: 4::: " + download);
String videoPath = download + "/" + name;
String chpName = name;
Log.v("log_tag", "chpName ::::" + chpName + " videoPath "
+ videoPath);
db.execSQL("insert into videoStatus (chapterNo,videoPath) values(\""
+ chpName + "\",\"" + videoPath + "\" )");
}
}
private void setProgress(final ProgressBar pr, final int position,
final Button Start, final Button cancel,
final DownloadFileFromURL downloadFileFromURL) {
ProgressBarSeek pbarSeek = new ProgressBarSeek();
pbarSeek.setPosition(position);
pbarSeek.setProgressValue(pr.getProgress());
//Log.v("log_tag", position + " progress " + pr.getProgress());
progreeSeekList.add(pbarSeek);
/* cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag","Cancle Button Click Set progress");
Start.setVisibility(View.VISIBLE);
cancel.setVisibility(View.GONE);
downloadFileFromURL.cancel(true);
pr.setProgress(0);
}
});
Start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag","Start Button Click set Progress");
str_start = list.get(position).url_video;
Start.setVisibility(View.GONE);
cancel.setVisibility(View.VISIBLE);
Log.v("log_tag", "str_start " + str_start);
//
// new DownloadFileFromURL().execute(str_start);
DownloadFileFromURL downloadFileFromU = new DownloadFileFromURL(
Start, cancel);
downloadFileFromU.execute(pr, str_start, position);
}
});*/
}
private void getProgress(ProgressBar pr, int position, Button cl, Button dl) {
if (progreeSeekList.size() > 0) {
for (int j = 0; j < progreeSeekList.size(); j++) {
if (position == progreeSeekList.get(j).getPosition()) {
pr.setProgress(progreeSeekList.get(j).getProgressValue());
dl.setVisibility(View.GONE);
cl.setVisibility(View.VISIBLE);
}
}
}
}
}
You can try using the below code to download the files from the url and save into the sdcard:
public void DownloadFromUrl(String DownloadUrl, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/xmls");
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); //you can write here any link
File file = new File(dir, fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager", "download url:" + url);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
}
Also keep in mind that you specify the below permissions in your manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
I hope it will help you.
Thanks

Android FTP file Uploading then Display Seekbar & network speed status issue

In my android project i need to display seekbar and network speed(With how much speed the file is Uploading/Downloading from server using FTP Protocol). In my situation when i try to upload a file from emulator sdcard then it's showing the speed and seekbar at the end when the file is stored in the server, but my requirement is i need to show sheekbar and network speed while the file is uploading into server. I am not understand where i did wrong in my code. In this attached image showing seekbar and TestAvarage speed for HTTP is fine like this i need to implement in FTP for upload a file to server. Below is my code for file upload using ftp to remote server:
Thanks In Advance.
#Override
protected String doInBackground(String... arg0) {
int count = 0;
FTPClient ObjFtpCon = new FTPClient();
//Toast.makeText(con, "FTPasync doInBackground() is called" ,Toast.LENGTH_SHORT).show();
try {
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(0);
//real_time.setText(0 + " secs");
//test_avg.setText(0+ " kbps");
//peak.setText(0+" kbps");
}
});
updateUI(pp, R.drawable.pause);
//ObjFtpCon.connect("ftp.customhdclips.com");
ObjFtpCon.connect("ftp."+map.get("url").toString());
updateUI(status, "Connecting");
//if (ObjFtpCon.login("fstech#customhdclips.com", "fstech123")) {
if (ObjFtpCon.login(map.get("username").toString(), map.get("password").toString())) {
updateUI(status, "Connected");
// toast("Connected to FTP Server : ftp.customhdclips.com");
ObjFtpCon.enterLocalPassiveMode(); // important!
ObjFtpCon.cwd("/");// to send the FTP CWD command to the server, receive the reply, and return the reply code.
//if (mode == 0) {
if(Integer.parseInt((map.get("oprn").toString()))== 0){
// Download
System.out.println("download test is called");
File objfile = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/logo.png");
/* * toast("Downloading /logo.png"); toast("File Size : "
* + objfile.getTotalSpace() + " bytes");*/
objfile.createNewFile();
FileOutputStream objFos = new FileOutputStream(objfile);
boolean blnresult = ObjFtpCon.retrieveFile("/logo.png",
objFos);
objFos.close();
if (blnresult) {
// toast("Download succeeded");
// toast("Stored at : " +
// objfile.getAbsolutePath());
}
//***********************************************************
/*
File objfile = new File(
Environment.getExternalStorageDirectory()
+ File.separator + "/test.txt");
// System.out.println("total" + objfile.getTotalSpace() + " bytes");
objfile.createNewFile();
FileOutputStream objFos = new FileOutputStream(objfile);
boolean blnresult = ObjFtpCon.retrieveFile("/test.txt",
objFos);
objFos.close();
if (blnresult) {
System.out.println("download in ftp is successful");
// toast("Download succeeded");
// toast("Stored at : " +
// objfile.getAbsolutePath());
}*/
}
else {
ObjFtpCon.connect("ftp."+map.get("url").toString());
updateUI(status, "Connecting");
ObjFtpCon.login(map.get("username").toString(), map.get("password").toString());
ObjFtpCon.enterLocalPassiveMode();
ObjFtpCon.cwd("/var/www/html/BevdogAnd");
ObjFtpCon.setFileType(FTP.BINARY_FILE_TYPE);
final long started = System.currentTimeMillis();
long sleepingTime= 0;
String sourceFileUri =extStorageDirectory+"/zkfile"+filename;
File secondLocalFile = new File(sourceFileUri);
long fileSize = secondLocalFile.length();
int sentBytes = 0;
InputStream inputStream = new FileInputStream(secondLocalFile);
System.out.println("Start uploading second file");
OutputStream outputStream = ObjFtpCon.storeFileStream(filename);
byte[] bytesIn = new byte[512];
int read = 0;
while ((read = inputStream.read(bytesIn)) != -1) {
updateUI(status, "Uploading");
outputStream.write(bytesIn, 0, read);
sentBytes+=read;
final int progress = (int) ((sentBytes * 100) / fileSize);
final long speed = sentBytes;
duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
if (duration != 0) {
//test_avg.setText((((speed / duration)*1000)*0.0078125) + " kbps");
test_avg.setText((speed / duration) / 1024 + " kbps");
if (pk <= (speed / duration) / 1024) {
pk = (speed / duration) / 1024;
}
/*if (pk <= ((speed / duration)*1000)*0.0078125) {
pk = (long)(((speed / duration)*1000)*0.0078125);
}*/
//peak.setText(pk + " kbps");
}
}
});
}
inputStream.close();
outputStream.close();
boolean completed = ObjFtpCon.completePendingCommand();
updateUI(status, "Completed");
if (completed) {
}
}
}
/*-------------------------------------------------------------*/
/*
URL url = new URL(map.get("url").toString());
URLConnection conexion = url.openConnection();
conexion.connect();
updateUI(status, "Connected");
final int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(
Environment.getExternalStorageDirectory()
+ File.separator
+ Info.getInfo(con).HTTP_DOWNLOAD_FILE_NAME);
byte data[] = new byte[1024];
long total = 0;
final long started = System.currentTimeMillis();
long sleepingTime= 0;
System.out.println("started time --"+started);
updateUI(status, "Downloading");
while ((count = input.read(data)) != -1) {
while (sleep) {
Thread.sleep(1000);
sleepingTime +=1000;
}
total += count;
final int progress = (int) ((total * 100) / lenghtOfFile);
final long speed = total;
duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
*/
/*-----------------------------------------------------------------------*/
else{
System.out.println("password entered is incorrect");
//Toast.makeText(con, "Username or/and password is incorrect", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e) {
e.printStackTrace();
// toast(e.getLocalizedMessage());
}
try {
ObjFtpCon.logout();
ObjFtpCon.disconnect();
}
catch (IOException e) {
e.printStackTrace();
// toast(e.getLocalizedMessage());
}
return null;
}
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if(fromUser){
mPlayer.seekTo(progress);
mSeekBar.setProgress(progress);
}
}
});

Categories

Resources