FILE TRANSFER in android - android

this is regarding android instant messenger. im trying to send a file, and this is how i send it :
#Override
public boolean sendFile(String path,String ip, int port) {
// TODO Auto-generated method stub
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
Log.i("SO sendFILE","null");
return false;
}
Log.i("SocketOP", "sendFILE-1");
File f = new File(path);
BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
FileInputStream fileIn = new FileInputStream(f);
Log.i("SocketOP", "sendFILE-2");
byte [] buffer = new byte [1024];
int bytesRead =0;
while ((bytesRead = fileIn.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
System.out.println("SO sendFile" + bytesRead);
}
out.flush();
out.close();
fileIn.close();
Log.i("SocketOP", "sendFILE-3");
} catch (IOException e) {
return false;
//e.printStackTrace();
}
// Toast.makeText(this, "Lvbvhhging...", Toast.LENGTH_SHORT).show();
return true;
}
this is how i receive connection and seperate text from file (i concatenate "text" to the output stream for the text)
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
this.fileSocket=socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
InputStream is=clientSocket.getInputStream();
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("Text") == true)
{
appManager.messageReceived(inputLine);
Log.i("SocketOP","text");}
else if
(inputLine.contains("Text") == false)
{
Log.i("SocketOP","filee");
appManager.fileReceived(is);
}
else{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
fileSocket.shutdownInput();
fileSocket.shutdownOutput();
fileSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
SocketOperator.this.sockets.remove(fileSocket.getInetAddress());
Log.i("SocketOP", "CLOSING CONNECTION");
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
and this is how i finally receive the file in a service called imService :
public void fileReceived(InputStream is)
throws FileNotFoundException, IOException {
Log.i("IMSERVICE", "FILERECCC-1");
if (is!= null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("/sdcard/chats/ffffff.txt");
bos = new BufferedOutputStream(fos);
byte[] aByte = new byte[1024];
int bytesRead = 0;
System.out.println("imService fileReceive" + bytesRead);
while ((bytesRead = is.read(aByte)) != -1) {
bos.write(aByte, 0, bytesRead);
System.out.println("imService fileReceive" + bytesRead);
}
bos.flush();
bos.close();
Log.i("IMSERVICE", "FILERECCC-2");
} catch (IOException ex) {
// Do exception handling
}
}
right where i receive the file connection and forward the inputstream IS to the file receive method, i see that its getting the bytes but once filereceived is called it isnt receving any bytes.
it uses tcp/ip.

ok, try it on your method
public void fileReceived(InputStream is)
throws FileNotFoundException, IOException
{
string result;
FileOutputStream fos = null;
fos = new FileOutputStream("/sdcard/chats/ffffff.txt");
Log.i("IMSERVICE", "FILERECCC-1");
if (is!= null)
{
// result = convertStreamToString(is);
// result = result.replace("\n", "");
// Log.e("InputStream output",result);
//IOUtils.copy(is,fos);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0)
{
fos.write(buffer, 0, length);
}
// Close the streams
fos.flush();
fos.close();
is.close();
}
}
/* public static String convertStreamToString(InputStream is)
throws Exception
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
return sb.toString();
}
*/
EDIT: make other stuff in fileReceived method as comment.. just paste my suggested code.
EDIT: its a IOUtils from apache use it..

Related

How to programatically download files with increased speed in android

Hi have implemented programatically downloading of file using inputstream and cipheroutputstream(for encryption). The download is happening very slow. Whereas if i try to download via download manager, it is very fast. What can i do to improve my code and increase the download speed of the file. Below is my code.
private void saveFileUsingEncryption(String aMineType, long length) throws Exception {
int bufferSize = 1024*4;
//byte[] buffer = new byte[1024];
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
long totalRead = 0;
FileOutputStream outStream = null;
File f = new File(Constants.DWLPATH);
if (!f.exists()) {
f.mkdirs();
}
try {
Cipher aes = Cipher.getInstance("ARC4");
aes.init(Cipher.ENCRYPT_MODE, new SecretKeySpec("mykey".getBytes(), "ARC4"));
if(contDisp==null || contDisp.length()==0) {
// downloadFileName = downloadFileName.replaceAll("[^a-zA-Z0-9_]+", "");
downloadFileName = downloadFileName + "." + getFileExtension(aMineType);
}
outStream = new FileOutputStream(Constants.DWLPATH + downloadFileName,true);
CipherOutputStream out = new CipherOutputStream(outStream, aes);
while ((bytesRead = inputStream.read(buffer, 0, bufferSize)) >= 0) {
out.write(buffer, 0, bytesRead);
try{
// Adjust this value. It shouldn't be too small.
Thread.sleep(50);
}catch (InterruptedException e){
TraceUtils.logException(e);
}
totalRead += bytesRead;
sb=sb.append("\n Total bytes Read:"+totalRead);
Log.e("--",sb.toString());
/* if (this.length > 0) {
Long[] progress = new Long[5];
progress[0] = (long) ((double) totalRead / (double) this.length * 100.0);
publishProgress(progress);
}*/
if (this.isCancelled()) {
if (conn != null)
conn.disconnect();
conn = null;
break;
}
}
Log.e("Download completed","success");
out.flush();
//Utils.putDownloadLogs(requestUrl,mimeType,length, downloadFileName,"Download is Successful",sb.toString(), context);
outStream.close();
buffer = null;
} catch (Exception e) {
TraceUtils.logException( e);
file_newsize = storedFileSizeInDB + totalRead;
if (totalFileSize == 0)
totalFileSize = length;
callback.onRequestInterrupted(file_newsize,totalFileSize);
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
// Utils.putDownloadLogs(requestUrl,mimeType,length,downloadFileName,"failure---" + errors.toString(),sb.toString(), context);
throw e;
} finally {
if (outStream != null)
outStream.close();
outStream = null;
}
}
You can use default download manager to download the file because its very easy to implement and provide better features like respond to the internet connection , provide accessibility to add notification in status bar , by running the query on download manager object you can find the total bytes and remaining bytes so you can calculate the progress and after completion of download by tapping the notification one can perform the desired operation.
And also there are many libraries are available for to achieve this like
PRDOWNLOADER
FetchDownloader
This libraires provide you the feature of pause,download, resume download , tracking the progress and cancel download
Also you can customize it as per your need.
Here is the DownloadAndEncryptFileTask.class to download with encryption
public class DownloadAndEncryptFileTask extends AsyncTask<Void, Void, Void> {
private String mUrl;
private File mFile;
private Cipher mCipher;
InputStream inputStream;
FileOutputStream fileOutputStream;
CipherOutputStream cipherOutputStream;
public DownloadAndEncryptFileTask(String url, File file, Cipher cipher) {
if (url == null || url.isEmpty()) {
throw new IllegalArgumentException("You need to supply a url to a clear MP4 file to download and encrypt, or modify the code to use a local encrypted mp4");
}
mUrl = url;
mFile = file;
mCipher = cipher;
}
private void downloadAndEncrypt() throws Exception {
URL url = new URL(mUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (mFile.length() > 0) {
connection.setRequestProperty("Range", "bytes=" + mFile.length() + "-");
}
connection.connect();
Log.e("length", mFile.length() + "");
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("server error: " + connection.getResponseCode() + ", " + connection.getResponseMessage());
}
inputStream = connection.getInputStream();
if (mFile.length() > 0) {
//connection.connect();
fileOutputStream = new FileOutputStream(mFile, true);
} else {
fileOutputStream = new FileOutputStream(mFile);
}
CipherOutputStream cipherOutputStream = new CipherOutputStream(fileOutputStream, mCipher);
byte buffer[] = new byte[1024 * 1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
Log.d(getClass().getCanonicalName(), "reading from http...");
cipherOutputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
cipherOutputStream.close();
connection.disconnect();
}
#Override
protected Void doInBackground(Void... params) {
try {
downloadAndEncrypt();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Log.d(getClass().getCanonicalName(), "done");
}
}
Call this class
new DownloadAndEncryptFileTask(
myFeedsModel.getVideo().getVideo360(),
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), myFeedsModel.getFile_name()),
OBJECT OF YOUR CIPHER

example of read file from assets

I'm working on example that make app read file from assets but it's not work, the text inside the (file.txt) doesn't appear.
code :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_file);
b_read= (Button)findViewById(R.id.b_read);
tv_text= (TextView) findViewById(R.id.tv_text);
b_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text="";
try{
InputStream is = getAssets().open("file.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
}catch (IOException ex) {
ex.printStackTrace();
}
tv_text.setText(text);
}
});
Can you help?
use this
StringBuilder DataString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = getAssets()
.open("file.txt", Context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
DataString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
tv_text.setText(DataString.toString());
even though your method is correct it would return 'android.content.res.AssetManager$AssetInputStream#[code]' some times
look at this answer and comments
In this example i'm reading tests.json from /assets folder:
public class Constants {
public static final String BASE_DIR = "arqospocket";
public static final String CONFIG_DIR = "cfg";
public static final String TESTS_DIR = "tests";
public static final String TESTS_FILE = "tests.json";
}
private String getJsonTestList() {
String path = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator
+ BASE_DIR
+ File.separator
+ TESTS_DIR;
final File file = new File(path, TESTS_FILE);
if(file.exists()){
Log.d(TAG, "getJsonTestList :: Reading tests from external file: " + file.getAbsolutePath());
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
return text.toString();
} catch (IOException e) {
Log.d(TAG, "getJsonTestList :: Exception reading from external file: " + e.getMessage());
}
}
//TODO remove this
Log.d(TAG, "getJsonTestList :: Reading tests from asset manager" );
AssetManager assetManager = getAssets();
ByteArrayOutputStream outputStream = null;
InputStream inputStream = null;
try {
inputStream = assetManager.open("tests.json");
outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[8192];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
} catch (IOException e) {
}
return outputStream.toString();
}

Recieving File with Socket in Android

I want to transfer a file between server and client, Server is a Windows program written in Delphi with Indy and Client is an Android
this is my client code for reading from socket :
...
InputStream IS = S.getInputStream();
byte[] FBytes = new byte[FileSize];
FileOutputStream FOS = new FileOutputStream(TempFile);
BufferedOutputStream BOS = new BufferedOutputStream(FOS);
int BytesRead = IS.read(FBytes);
int CurrProgress = BytesRead;
do {
Log.d("DOWNLOAD", "BytesRead2 = " + Integer.toString(BytesRead));
if(CurrProgress < FBytes.length) {
Log.d("DOWNLOAD", "prog < BytesRead" );
BytesRead = IS.read(FBytes);
if (BytesRead > 0)
CurrProgress += BytesRead;
B.clear();
B.putInt("ProgValue", CurrProgress);
Msg.what = MSG_FILE_PROGRESS;
Hdlr.dispatchMessage(Msg);
Log.d("DOWNLOAD", "BytesRead = " + Integer.toString(BytesRead));
}
} while (BytesRead > 0);
Log.d(TAG, "Download Loop Finished");
File will download but the problem is size of downloaded file is lower than original file and the socket read command stay on last read. in other words file has been downloaded but CurrProgress is lower than FBytes.length so while loop execute onetime more and program hangs on read command because there is no more data sent from server
I have been tested server with an windows program and there is no problem in the server code
I have tested many ways like this but no chance :
int BytesRead = IS.read(FBytes, 0, FBytes.length);
int CurrProgress = BytesRead;
do {
Log.d("DOWNLOAD", "BytesRead2 = " + Integer.toString(BytesRead));
if(CurrProgress < FBytes.length) {
Log.d("DOWNLOAD", "prog < BytesRead" );
BytesRead = IS.read(FBytes, CurrProgress, (FBytes.length - CurrProgress));
...
FileSize value is correct and came from server as a string value before reading file bytes
What goes wrong ?!, thanks ...
Edit :
Complete code do many other jobs but code of reading file is like this :
public void Run()
{
Running = true;
try{
try{
InetAddress ServerAddr = InetAddress.getByName(SERVER_IP);
S = new Socket(ServerAddr, SERVER_PORT);
Log.d(TAG, "Connecting ...");
Out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(S.getOutputStream())), true);
In = new BufferedReader(new InputStreamReader(S.getInputStream()));
switch (Job) {
...
}
case GetFile: {
this.SendMessage(Cmd);
response = In.readLine();
if(response.equals("1"))
{
Hdlr.sendEmptyMessage(MSG_SERVER_ACCEPT);
response = In.readLine();
int FileSize = Integer.parseInt(response);
if (context.getFilesDir().getFreeSpace() < 3 * FileSize)
{
Hdlr.sendEmptyMessage(MSG_ERROR_FREESPACE);
Log.d(TAG, "There is no Free Space !");
}
else {
final Message Msg = new Message();
final Bundle B = new Bundle();
B.putInt("FSize", FileSize);
Msg.what = MSG_FILE_SIZE;
Msg.setData(B);
Hdlr.dispatchMessage(Msg);
try {
File TempDir, TempFile, MainDir, MainFile;
switch(FileType)
{
case 2 :
TempDir = new File(context.getCacheDir(), "TempMP3");
if(!TempDir.exists()) {
TempDir.mkdir();
}
TempFile = new File(TempDir, Integer.toString(FileIndex) + ".mp3");
if(TempFile.exists()) {
TempFile.delete();
}
break;
default :
TempDir = new File(context.getCacheDir(), "TempLevel");
if(!TempDir.exists()) {
TempDir.mkdir();
}
TempFile = new File(TempDir, Integer.toString(FileIndex) + ".zip");
if(TempFile.exists()) {
TempFile.delete();
}
}
InputStream IS = S.getInputStream();
byte[] FBytes = new byte[4096];
FileOutputStream FOS = new FileOutputStream(TempFile);
BufferedOutputStream BOS = new BufferedOutputStream(FOS);
int BytesRead = 0;
int CurrProgress = 0;
do {
Log.d("DOWNLOAD", "prog < BytesRead" );
BytesRead = IS.read(FBytes, 0, FBytes.length);
BOS.write(FBytes, 0, BytesRead);
if (BytesRead > 0)
CurrProgress += BytesRead;
B.clear();
B.putInt("ProgValue", CurrProgress);
Msg.what = MSG_FILE_PROGRESS;
Hdlr.dispatchMessage(Msg);
Log.d("DOWNLOAD", "BytesRead = " + Integer.toString(BytesRead));
} while (CurrProgress < FileSize);
Log.d(TAG, "Download Loop Finished");
if (CurrProgress != FBytes.length) {
BOS.close();
Hdlr.sendEmptyMessage(MSG_ERROR_FILESIZE);
Log.d(TAG, "File Size Problem");
} else {
BOS.close();
Log.d(TAG, "File Downloaded successfully, Preparing to Unzip ... ");
try {
MainDir = new File(context.getFilesDir(), "Levels");
if(!MainDir.exists())
{
MainDir.mkdir();
}
File LevelDir = new File(MainDir, Integer.toString(FileIndex));
if(!LevelDir.exists())
{
LevelDir.mkdir();
}
else
{
LevelDir.delete();
}
FileInputStream fin = new FileInputStream(TempFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
MainFile = new File(LevelDir, ze.getName());
FileOutputStream FOut = new FileOutputStream(MainFile);
for (int c = zin.read(); c != -1; c = zin.read()) {
FOut.write(c);
}
zin.closeEntry();
FOut.close();
}
zin.close();
} catch (Exception e) {
Log.d(TAG, "Unzip Error : ", e);
}
}
} catch (Exception E) {
Err = 1;
Log.d(TAG, "Get File Error : ", E);
}
}
}
else
{
if (Listener != null)
{
Listener.callbackMessageReceiver(response);
Hdlr.sendEmptyMessage(MSG_ERROR_SERVER);
}
}
break;
}
...
}
}catch (Exception e)
{
Hdlr.sendEmptyMessage(MSG_ERROR_SEND);
Log.d(TAG, "Connect Error : ", e);
}
finally{
if(Out != null) {
Out.flush();
Out.close();
}
if(In != null)
{
In.close();
}
S.close();
Log.d(TAG, "Err Value is : " + Integer.toString(Err));
if(Err == 0)
{
Hdlr.sendEmptyMessage(MSG_SUCCESS);
}
Log.d(TAG, "Sending Ends");
}
}catch (Exception E){
Log.d(TAG, "Error : ", E);
}
}
CurrProgress is lower than FileSize ( the difference is about 4 or 5 KB ) and the while loop hangs on read command !
Problem solved, I will post it as answer, it may be useful
The problem was that server sends File immediately after sending FileSize and I think the BufferedReader gets some bytes of File so the size of bytes given by IS are lower than FileSize, example of Server :
...
WriteLn(FileSize);
Write(FileStream);
...
Now, Server first sends FileSize then wait for a response from client, after checking freespace in client it sends a Ready response to server and then Server sends the File Stream, for example :
...
WriteLn(FileSize);
Response := ReadLn();
if Response = "READY" then
Write(FileStream);
...
and codes in client are like this :
...
BufferedInputStream BIS = new BufferedInputStream(S.getInputStream());
In = new BufferedReader(new InputStreamReader(S.getInputStream()));
...
response = In.readLine();
int FileSize = Integer.parseInt(response);
if (context.getFilesDir().getFreeSpace() < 3 * FileSize)
{
Hdlr.sendEmptyMessage(MSG_ERROR_FREESPACE);
Log.d(TAG, "There is no Free Space !");
this.SendMessage("NOT_READY");
}
else {
...
try {
this.SendMessage("READY");
byte[] FBytes = new byte[8192];
FileOutputStream FOS = new FileOutputStream(TempFile);
BufferedOutputStream BOS = new BufferedOutputStream(FOS);
int BytesRead = 0;
int CurrProgress = 0;
while (CurrProgress < FileSize){
Log.d("DOWNLOAD", "Available : " + Integer.toString(BIS.availabl
BytesRead = BIS.read(FBytes, 0, FBytes.length);
BOS.write(FBytes, 0, BytesRead);
if (BytesRead > 0)
CurrProgress += BytesRead;
B.clear();
B.putInt("ProgValue", CurrProgress);
Msg.what = MSG_FILE_PROGRESS;
Hdlr.dispatchMessage(Msg);
Log.d("DOWNLOAD", "BytesRead = " + Integer.toString(BytesRead));
}
There is no problem and everything works fine

Reading xml content in android

I have an xml file in my Android project.
It contains a simple list of employee ids.
I want to read the below xml content.
I placed this file in res/raw/
saplist.xml
<?xml version="1.0" encoding="UTF-8"?>
<EMPNOLIST>
<EMPID>“12345”</EMPID>
<EMPID>“23456”</EMPID>
<EMPID>“34567”</EMPID>
</EMPNOLIST>
Code to read it
{
// Load XML for parsing.
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("saplist.xml");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
String s = readTextFile(inputStream);
Log.e("FMApp: ", s);
}
private String readTextFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
This code doesn't read the xml content.
Instead, it crashes.
Could someone help me on how to read such a simple xml?
You can check http://developer.android.com/training/basics/network-ops/xml.html to read xml data.
You first closed the outputStream and then returned outputStream.toString() that isn't going to work.
private String readTextFile(InputStream inputStream) {
String result = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
result = outputStream.toString()
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return result;
}

android progressbar

hi could some one show me how to add a progress bar to this method :
public boolean sendFile(String path,String ip, int port) {
// TODO Auto-generated method stub
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
Log.i("SO sendFILE","");
return false;
}
Log.i("SocketOP", "sendFILE-1");
File f = new File(path);
String filename=path.substring(path.lastIndexOf("/")+1);
System.out.println("filename:"+filename);
fin.filename = "~"+filename;
BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
FileInputStream fileIn = new FileInputStream(f);
Log.i("SocketOP", "sendFILE-2");
byte [] buffer = new byte [(int)f.length()];
System.out.println("SO sendFile f.length();" + f.length());
int bytesRead =0;
while ((bytesRead = fileIn.read(buffer)) > 0) {
out.write(buffer, 0, buffer.length);
System.out.println("SO sendFile" + bytesRead +filename);
}
out.flush();
out.close();
fileIn.close();
Log.i("SocketOP", "sendFILE-3");
} catch (IOException e) {
return false;
//e.printStackTrace();
}
// Toast.makeText(this, "Lvbvhhging...", Toast.LENGTH_SHORT).show();
return true;
}
thanks in advance.
ProgressDialog pbarDialog = new ProgressDialog( mContext );
pbarDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pbarDialog.setMessage("Loading...");
pbarDialog.setCancelable(false);
pbarDialog.setMax(100);
pbarDialog .setProgress(0);
pbarDialog.show();
while ((bytesRead = fileIn.read(buffer)) > 0) {
out.write(buffer, 0, buffer.length);
//get the previous value of progress bar
int old_value = pbarDialog .getProgress();
//calculate how much did you read from the file
int new_read =(int)( ((float) bytesRead/f.length()) )*100 ) ;
//add the new read to the old_value
int value = new_read+old_value;
pbarDialog.setProgress(value);
System.out.println("SO sendFile" + bytesRead +filename);
}
pbarDialog.dismiss();
You would need to run that function from the UI thread in order to show a progress bar, but then you wouldn't get to see any progress until the function finished. The right approach for what you are trying to do is an AsyncTask, check
http://developer.android.com/reference/android/os/AsyncTask.html

Categories

Resources