Reputation: 50
I am making an Android application to transfer files from the device to a Java application on a computer. It works in the sense that it can send files to the computer, but while it sends it has a ProgressDialog
. The dialog is not meant to monitor the progress of reading from the SD card, but instead the progress of uploading to the server. So far my searches have only come up with reading from a SD card or a webpage.
To upload, I am using a simple OutputStream
that is created with socket.getOutputStream();
. My code is as follows:
protected void onProgressUpdate(Integer... values) {
mProgressDialog.setIndeterminate(false);
mProgressDialog.setProgress(progress);
}
@Override
protected String doInBackground(String[] params) {
String IP = params[1];
File myFile = new File(params[0]);
int count;
try {
long total = 0;
Socket socket = new Socket(IP, 25000);
byte[] buffer = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream in = new BufferedInputStream(fis);
OutputStream out = socket.getOutputStream(); // THIS IS MY OUTPUTSTREAM
while((count = in.read(buffer, 0, buffer.length)) != -1) {
total += count;
progress = (int) (count);
publishProgress();
out.write(buffer, 0, buffer.length);
Log.i("TOTAL", Long.toString(total));
Log.i("Upload progress", "" + (int) ((total * 100) / buffer.length));
}
out.flush();
out.close();
in.close();
socket.close();
} catch(Exception ex) {
ex.printStackTrace();
Log.i("TAG", "Failed to send file");
}
return "test";
}
From my research on the documentation and other forums, it seems like OutputStream has no methods that return anything. This is troublesome as I need to return its current status on the upload.
As of right now, the progress dialog goes from 0 to max instantly regardless of the file size (it just takes much longer to actually do so). I don't know what could be causing this, but that's not the point.
How can I monitor the upload progress of a file using OutputStream? Is this possible to do?
Thanks in advance.
Upvotes: 0
Views: 1384
Reputation: 46
Your problem is you have created buffer with your file size:
byte[] buffer = new byte[(int) myFile.length()];
So you cycle passes only 1 time because is enough space for data
while((count = in.read(buffer, 0, buffer.length)) != -1)
You need to change on something like this:
byte[] buffer = new byte[256];
Upvotes: 1