Async only works when stepping through debugger - java

I've been getting very strange behavior from my code.
Basically, my code is using an Input/Output stream to download a .pdf file from the internet, saving it to internal storage (using an AsyncTask) and then outputting it using an outside "showPdf" library.
The strangest thing is that it only works on two conditions:
I run the code twice (run or debug without any break points). The first run logs File is empty when showPdf() is called, but the second run through runs perfectly fine when showPdf() is called on its own.
I debug the code and step through the program
As a preface, I'm new to java and android studio, so my guess may not be right at all, but I'm guessing since the InputStream is being done "asynchronously", showPdf() may be called before the byte[] array is written into memory. If this is the case, what could I do to delay Async long enough to work?
public class pdfView extends AppCompatActivity {
PDFView pdfView; //pdfView object
String URL;
String fileName;
File directory; //path of created File
// Container for all parameters of DownloadAsync
private static class AsyncParameters {
String URL;
File directory;
AsyncParameters(String URL, File directory) {
this.URL = URL;
this.directory = directory;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf_view);
//Grab the extras from the intent call
Intent intent = getIntent(); //whatever calls this activity, gather the intent
URL = intent.getStringExtra("File URL"); // in this case, get the file name of the "extra" passed through
fileName = intent.getStringExtra("File Name");
//Grab the internal storage directory and create a folder if it doesn't exist
File intDirectory = getFilesDir();
File folder = new File(intDirectory, "pdf");
boolean isDirectoryCreated = folder.exists();
//See if the file exists
if (!isDirectoryCreated) {
isDirectoryCreated= folder.mkdir();
}
if(isDirectoryCreated) {
directory = new File(folder, fileName);
try {
directory.createNewFile();
if (directory.canWrite())
Log.d("hngggggggggggggg", "onCreate: ");
} catch (IOException e1) {
e1.printStackTrace();
}
//See if file already exists
boolean empty = directory.length() == 0;
if (empty){
/**Call class to create parameter container**/
AsyncParameters param = new AsyncParameters(URL, directory);
DownloadAsync Downloader = new DownloadAsync();
Downloader.execute(param);
showPdf();
}
else
showPdf();
}
}
public void showPdf()
{
pdfView = (PDFView) findViewById(R.id.pdfView);
pdfView.fromFile(directory).load();
}
/**Class for asynchronous tasks**/
public class DownloadAsync extends AsyncTask<AsyncParameters, Void, Void> {
// Container for all parameters of DownloadAsync
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(pdfView.this);
pDialog.setMessage("Downloading Database...");
String message= "Downloading Files";
SpannableString ss2 = new SpannableString(message);
ss2.setSpan(new RelativeSizeSpan(2f), 0, ss2.length(), 0);
ss2.setSpan(new ForegroundColorSpan(Color.BLACK), 0, ss2.length(), 0);
pDialog.setMessage(ss2);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(AsyncParameters... params) {
Log.d("WE ARE IN DOBACKGROUND", "doInBackground: ");
String fileURL = params[0].URL;
File directory = params[0].directory;
try {
FileOutputStream f = new FileOutputStream(directory);
java.net.URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[8192];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
onPostExecute();
return null;
}
protected void onPostExecute() {
pDialog.dismiss();
}
}
}

You already have answered your own question. Since the download is asyncTask running on a different thread, there is no wait for the asyncTask to complete before showPdf() is called. You can call showPdf() from onPostExecute() which is called after the background task completes. Your code should look like:
#Override
protected void onCreate(Bundle savedInstanceState) {
........
........
AsyncParameters param = new AsyncParameters(URL, directory);
DownloadAsync Downloader = new DownloadAsync();
Downloader.execute(param);
.......
.......
}
public class DownloadAsync extends AsyncTask<AsyncParameters, Void, Void> {
.......
#Override
protected void onPostExecute() {
pDialog.dismiss();
showPdf();
}
}

Related

Where should I put my AsyncTask class for my app?

So I have been trying to make a feature in my app where I can login and then fetch data from my database through the Django REST Framework. My logging in works as it only uses POST, but retrieving items does not work.
For some reason my AsyncTask does not get called for retrieving posts.
I have placed my AsyncTask for both activities, which are login and posts, on a separate java file only for handling Web Server stuff.
I am wondering if this is because I should put AsyncTask on each activities.
login.java
public class Login extends AppCompatActivity {
Button LoginButton;
EditText uUserName, uPassWord;
WSAdapter.SendAPIRequests AuthHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn);
LoginButton = (Button) findViewById(R.id.LoginButton);
uUserName = (EditText) findViewById(R.id.LoginUserBox);
uPassWord = (EditText) findViewById(R.id.LoginPassBox);
//AuthHelper = new WSAdapter().new SendDeviceDetails();
// Moves user to the main page after validation
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// gets the username and password from the EditText
String strUserName = uUserName.getText().toString();
String strPassWord = uPassWord.getText().toString();
// API url duh
String APIUrl = "http://192.168.0.18:8000/token-auth/";
// If the user is authenticated, then transfer to the MainActivity page
if (APIAuthentication(strUserName, strPassWord, APIUrl)){
startActivity(new Intent(Login.this, Posts.class));
}
}
});
}
private boolean APIAuthentication(String un, String pw, String url){
// when it wasn't static -> AuthHelper = new WSAdapter().new SendAPIRequests();
AuthHelper = new WSAdapter.SendAPIRequests();
JSONObject postData = new JSONObject();
try {
// Attempt to input info to the Django API
postData.put("username", un);
postData.put("password", pw);
// Putting the data to be posted in the Django API
AuthHelper.execute(url, postData.toString());
return true;
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
posts.java
public class Posts extends AppCompatActivity {
TextView postsSect;
Button postsDoneBtn;
WSAdapter.SendAPIRequests PostsHelper;
StringBuilder postsBuffer = new StringBuilder();
#Override
protected void onResume(){
super.onResume();
PostsDetails postDetailsHelper = new PostsDetails();
postDetailsHelper.ListPosts();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
PostsDetails postDetailsHelper = new PostsDetails();
postsDoneBtn = (Button) findViewById(R.id.PostsDoneButton);
postDetailsHelper.callPostDetails("192.168.0.18:8000/api");
postDetailsHelper.ListPosts();
postDetailsHelper.postDetailsCalled('n');
postsDoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Posts.this, MainActivity.class));
}
});
}
public class PostsDetails {
//String post_title, post_content;
ArrayList<Integer> post_id = new ArrayList<Integer>();
ArrayList<String> post_title = new ArrayList<String>();
ArrayList<String> post_content = new ArrayList<String>();
boolean isPDCalled;
// sets if Post details are called
boolean postDetailsCalled(char called) {
if (called == 'y'){
return true;
}
return false;
}
// checks if postsDetails functions are called for AsyncTask
boolean getIsPDCalled(){
return isPDCalled;
}
// calls the execute for AsyncTask
private void callPostDetails(String theurl){
PostsHelper = new WSAdapter.SendAPIRequests();
// sets if post details are called
postDetailsCalled('y');
// executes AsyncTask
PostsHelper.execute(theurl);
}
// sets values for the posts arrays
public void setPost(int p_id, String p_title, String p_content) {
post_id.add(p_id);
post_title.add(p_title);
post_content.add(p_content);
}
// Lists the posts from the database
public void ListPosts() {
/////////// add functionality if a post was deleted and was clicked
postsSect = (TextView) findViewById(R.id.PostsSection);
postsSect.setText(post_title.get(post_title.size()) + "\n");
for (int i = post_id.size() - 1; i > 0; i--)
{
postsSect.append(post_title.get(i));
}
}
}
}
WSAdapter.java
// I forgot what WS stands for, but this class serves as an adapter for JSON and Online stuff
// I think it stands for With-Server Adapter
public class WSAdapter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
static public class SendAPIRequests extends AsyncTask<String, String, String> {
// Add a pre-execute thing
#Override
protected String doInBackground(String... params) {
Log.e("TAG", params[0]);
Log.e("TAG", params[1]);
String data = "";
HttpURLConnection httpURLConnection = null;
try {
// Sets up connection to the URL (params[0] from .execute in "login")
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
// Sets the request method for the URL
httpURLConnection.setRequestMethod("POST");
// Tells the URL that I am sending a POST request body
httpURLConnection.setDoOutput(true);
// To write primitive Java data types to an output stream in a portable way
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
// Writes out a byte to the underlying output stream of the data posted from .execute function
wr.writeBytes("postData=" + params[1]);
// Flushes the postData to the output stream
wr.flush();
wr.close();
// Representing the input stream
InputStream in = httpURLConnection.getInputStream();
// Preparing input stream bytes to be decoded to charset
InputStreamReader inputStreamReader = new InputStreamReader(in);
StringBuilder dataBuffer = new StringBuilder();
// Translates input stream bytes to charset
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
// concatenates data characters from input stream
dataBuffer.append(current);
}
data = dataBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Disconnects socket after using
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Log.e("TAG", data);
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// For posts
try {
if (postsHelper.getIsPDCalled()){
JSONObject pJObj = new JSONObject(result);
JSONArray pJObjArray = pJObj.getJSONArray("posts");
for (int i = 0; i < pJObjArray.length(); i++) {
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
postsHelper.setPost(pJObj_data.getInt("id"), "post_title", "post_content");
}
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
}
}
Yes, you can and should put the network calls functions in a separate java file for better readability and test-coverage.
Apart from that, i would suggest to use Retrofit as your HTTP client. It helps you to manage all the dirty things like headers and converters etc, so you can put all your effort on your logic and implementing your callback actions.

How to return package name from txt file on server

So I have an activity that goes to my server a fetches a text file. This text file holds one line of text containing a package name. My goal is to fetch the package name then use the package name to get the versionCode of the package specified in the txt file on the server.
Here is the class that fetches the txt file from the server:
public class getter extends Activity {
Activity context;
TextView txtview;
ProgressDialog pd;
protected void onCreate(Bundle savedInstanceState) {
//TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get);
context=this;
}
public void onStart(){
super.onStart();
BackTask bt=new BackTask();
bt.execute("http://1.2.3.4/test.txt");
}
//background process to download the file from internet
public static class BackTask extends AsyncTask<String,Integer,Void>{
String text="";
protected void onPreExecute(){
super.onPreExecute();
//display progress dialog
}
protected Void doInBackground(String...params){
URL url;
try {
//create url object to point to the file location on internet
url = new URL(params[0]);
//make a request to server
HttpURLConnection con=(HttpURLConnection)url.openConnection();
//get InputStream instance
InputStream is=con.getInputStream();
//create BufferedReader object
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line;
//read content of the file line by line
while((line=br.readLine())!=null){
text+=line;
}
br.close();
}catch (Exception e) {
e.printStackTrace();
//close dialog if error occurs
}
return null;
}
protected void onPostExecute(Void result){
String packageName = text;
}
}
public String getPackageName(Context mContext) {
if (mContext != null) {
BackTask bt=new BackTask();
bt.execute("http://1.2.3.4/test.txt");
}
return "";
}
}
And this is supposed to get the versionCode from the package specified on the server:
public static int getinstVersionCode(Context mContext) {
if (mContext != null) {
try {
getter.BackTask bt=new getter.BackTask();
bt.execute("http://1.2.3.4/test.txt");
return mContext.getPackageManager().getPackageInfo(String.valueOf(new getter.BackTask().execute("http://1.2.3.4/test.txt")), 0).versionCode;
} catch (PackageManager.NameNotFoundException ignored) {
}
}
return 0;
}
Why doesn't this return the versionCode of the package name on the server?
I think the error lies in the function below but I am not sure.
return mContext.getPackageManager().getPackageInfo(String.valueOf(new getter.BackTask().execute("http://1.2.3.4/test.txt")), 0).versionCode;
One issue is that your variable packageName in onPostExecute is local to that method. So even if that method gets called correctly, no other method would see that value.
You could try to declare packageName near the top of BackTask, near where you declare the variable text.
Then change this method to:
protected void onPostExecute(Void result){
packageName = text;
}
Disclaimer: I have not attempted to load and run your code or this fix!
if the network didn't have any issue then think the issue is caused because you communicate between the doInBackground and onPostExecute using a variable inside the the AsyncTask => text
you should using the return value on the doInBackground to pass it to the onPostExecute
change the Asynctask to
//background process to download the file from internet
public static class BackTask extends AsyncTask<String,Integer,String>{
protected void onPreExecute(){
super.onPreExecute();
//display progress dialog
}
protected String doInBackground(String...params){
URL url;
String text;
try {
//create url object to point to the file location on internet
url = new URL(params[0]);
//make a request to server
HttpURLConnection con=(HttpURLConnection)url.openConnection();
//get InputStream instance
InputStream is=con.getInputStream();
//create BufferedReader object
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line;
//read content of the file line by line
while((line=br.readLine())!=null){
text+=line;
}
br.close();
}catch (Exception e) {
e.printStackTrace();
//close dialog if error occurs
}
return text;
}
protected void onPostExecute(String resultText){
String packageName = resultText;
}
}
You have twice
new getter.BackTask().execute("http://1.2.3.4/test.txt")).
Why? Looks no good.
Further you cannot get results from an AsyncTask with
String.valueOf(new getter.BackTask().execute("http://1.2.3.4/test.txt"))
You should handle the result of doInBackground in onPostExecute. Only there!

How can I resume my download by onResume() in android?

My application has a "start download" and a "pause" button. Once I start the download through "Start Download" button my download starts and stop upon clicking "pause" now when I press back or home button the onPause() function works as intended it pauses my download and when I open the app again and click start it resumes from that progress,
what I want is that upon switching back(not the first time load of app) to the application once I have pressed back or home I want the download to resume automatically by onResume without clicking start button again. Right now in below code my download automatically starts without doing anything which is due to my onResume(), is it possible that I can resume with onResume but not start the download automatically upon first time loading of the app thorugh it? I know the below code is not as efficient as it could have been. Apologies for that.
Again, I want my onResume to only resume my previously downloaded file not start the download unless download was once initiated through the button.
public class MainActivity extends Activity implements OnClickListener{
String url = "http://upload.wikimedia.org/wikipedia/commons/1/11/HUP_10MB_1946_obverse.jpg";
boolean mStopped=false;
private ProgressBar progressBar2;
private String filepath = "MyFileStorage";
private File directory;
private TextView finished;
#Override
protected void onPause() {
super.onPause();
mStopped=true;
}
#Override
protected void onResume() {
super.onResume();
mStopped=false;
grabURL(url);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
progressBar2 = (ProgressBar) findViewById(R.id.progressBar2);
progressBar2.setVisibility(View.GONE);
finished = (TextView) findViewById(R.id.textView1);
finished.setVisibility(View.GONE);
Button stop = (Button) findViewById(R.id.stop);
stop.setOnClickListener(this);
Button download = (Button) findViewById(R.id.download);
download.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.stop:
mStopped=true;
break;
case R.id.download:
mStopped=false;
grabURL(url);
break;
}
}
public void grabURL(String url) {
new GrabURL().execute(url);
}
private class GrabURL extends AsyncTask<String, Integer, String> {
protected void onPreExecute() {
progressBar2.setVisibility(View.VISIBLE);
progressBar2.setProgress(0);
finished.setVisibility(View.GONE);
}
protected String doInBackground(String... urls) {
String filename = "MySampleFile.png";
File myFile = new File(directory , filename);
try {
URL url = new URL(urls[0]);
URLConnection connection = url.openConnection();
if (myFile.exists())
{
connection.setAllowUserInteraction(true);
connection.setRequestProperty("Range", "bytes=" + myFile.length() + "-");
}
connection.connect();
int fileLength = connection.getContentLength();
fileLength += myFile.length();
InputStream is = new BufferedInputStream(connection.getInputStream());
RandomAccessFile os = new RandomAccessFile(myFile, "rw");
os.seek(myFile.length());
byte data[] = new byte[1024];
int count;
int __progress = 0;
while ((count = is.read(data)) != -1 && __progress != 100) {
if (mStopped) {
throw new IOException();
}
else{
__progress = (int) ((myFile.length() * 100) / fileLength);
publishProgress((int) (myFile.length() * 100 / fileLength));
os.write(data, 0, count);}
}
os.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return filename;
}
protected void onProgressUpdate(Integer... progress) {
finished.setVisibility(View.VISIBLE);
finished.setText(String.valueOf(progress[0]) + "%");
progressBar2.setProgress(progress[0]);
}
protected void onCancelled() {
Toast toast = Toast.makeText(getBaseContext(),
"Error connecting to Server", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
protected void onPostExecute(String filename) {
progressBar2.setProgress(100);
finished.setVisibility(View.VISIBLE);
finished.setText("Download in progress..");
File myFile = new File(directory , filename);
ImageView myImage = (ImageView) findViewById(R.id.imageView1);
myImage.setImageBitmap(BitmapFactory.decodeFile(myFile.getAbsolutePath()));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
You seem to already have most of the code in place for the functionality. In onResume you can call your ASyncTask and it should start download if the file exists (paused download in onPause(), file exists). I have written similar code, you can find it here: https://github.com/hiemanshu/ContentDownloader/blob/master/src/com/example/contentdownloader/MainActivity.java
In my code you can find that instead of using onPause and onResume, I just have a wakelock for that period of time.

Android programming (Trying to download a file to system directory)

Dear stackOverflow members i have recently started a new project called "RootBox" and it is an app that needs "su" perms and i have successfully allowed the app "su" or "root" access and im trying to download and replace a system file in "/system/media and i have setup my downloader but the download progress dialog pops up and closes which im guessing is the result of the file not being able to written to the system directory and i have Re-mounted the system as r-w before starting the download an i have searched all over the internet and was unable to find help thats why i have come here.
This is the activity executing the download
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bootmation);
startBtn = (Button)findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startDownload();
RootTools.remount("/system/", "rw");
}
});
}
private void startDownload() {
String url = "http://www.filehosting.org/file/details/430746/bootanimation.zip";
new DownloadFileAsync().execute(url);
}
#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;
}
}
class DownloadFileAsync extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
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("/system/media/bootanimation.zip");
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]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
for this u have to allow in manifest for permission for writing as
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
URL u = new URL(fUrls[i]);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();

FTPClient (commons net) download and logout don't work

I'm apologise for my english.
I use the following piece of code to download a file from ftp host to Tablet. When I use Wi-Fi everything works well. But when I try to download a file using the mobile Internet, the download stops, but not always, sometimes finishes normally. I've found that stop is always going on "retrieveFile" or "logout", the program comes to these commands and no going further, and simply stands, the icon of data transfer does not blink, stops occur randomly. I tried to use different mobile operators, but there is no difference. What could be the reason?
And another question, but It is not so important, I've not found how to get the file size, and used my decision, maybe there is another way to get the file size ?
private void downloadFile(final String url, final String Message, final String Message2, final Uri uri) {
final ProgressDialog progressDialog = new ProgressDialog(this);
new AsyncTask() {
private Exception m_error = null;
#Override
protected void onPreExecute() {
progressDialog.setMessage(Message);
progressDialog.setCancelable(true);
progressDialog.setMax(100);
progressDialog
.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
}
#Override
protected File doInBackground(String... params) {
FileOutputStream fos = null;
File file = null;
FTPClient client = null;
try{
client = new FTPClient();
client.connect(ftp_host,Integer.parseInt(ftp_port));
client.login(ftp_user, ftp_password);
client.enterLocalPassiveMode();
client.setFileType(FTP.BINARY_FILE_TYPE);
String stat = "";
if (url.equals("MobiTrade.apk")){
client.changeWorkingDirectory("/var/srv/home/user/mobitrade/update/");}
file = new File(Environment.getExternalStorageDirectory(),
"/MobiTrade/update/MobiTrade.apk");}
stat = client.getStatus("/var/srv/home/user/mobitrade/update/MobiTrade.apk");
else {
client.changeWorkingDirectory("/var/srv/home/user/mobitrade/"+number+"/out/");
file = new File(Environment.getExternalStorageDirectory(),
"/MobiTrade/in/"+url);
if (url.equals("message.csv")) file.delete();
stat = client.getStatus("/var/srv/home/user/mobitrade/"+number+"/out/"+url);
}
final Integer FileSize;
if (stat.length() >= 64) {
stat = stat.substring(49,64);
stat = stat.trim();
FileSize = Integer.parseInt(stat);
}
else {
FileSize = 0;
}
fos = new FileOutputStream(file);
CountingOutputStream cos = new CountingOutputStream(fos){
protected void beforeWrite(int n){
super.beforeWrite(n);
publishProgress(getCount(), FileSize);
}
};
if (url.equals("MobiTrade.apk")){
client.retrieveFile("/var/srv/home/user/mobitrade/update/MobiTrade.apk", cos);
}
else {
client.retrieveFile("/var/srv/home/user/mobitrade/"+number+"/out/"+url, cos);
}
if (url.equals("message.csv")){
client.deleteFile("/var/srv/home/user/mobitrade/"+number+"/out/"+url);
}
client.logout();
}
catch (Exception e){
e.printStackTrace();
}
finally{
try{
if (fos != null) fos.close();
if (client.isConnected()) {
client.disconnect();
}
}
catch (IOException e){
e.printStackTrace();
}
}
return file;
}
protected void onProgressUpdate(Integer... values) {
progressDialog
.setProgress((int) ((values[0] / (float) values[1]) * 100));
};
#Override
protected void onPostExecute(File result) {
if (m_error != null) {
m_error.printStackTrace();
return;
}
progressDialog.hide();
if (url.equals("settings.csv"))
ProcessSettings(url);
else if (url.equals("MobiTrade.apk"))
ProcessUpdate();
else
ProcessData(url, Message2, uri);
}
}.execute(url);
}
Any help would be appreciable.

Categories