Thursday, March 21, 2013

Android: Downloading a file from Server and save it into SD card with progress bar


Android: Downloading a file from Server and save it into SD card with progress bar


Hi to all,
Now i am  going to explain here about how to download file from remote server and save it in SD card.
For this tutorial i assumed that you might have good in Android application development with popular IDE Eclipse.
So lets start to see how this happen in Android.

First of all you need to create a demo application in eclipse.
For me i have created Android Demo.
Create an class which is you launching point of your application.

Here, i called it MainActivity.java which extends the Activity.
Now, before we go in detail we need to give some permission to our
application on mobile device operating system so it can utilize the mobile features.

For internet connectivity we need to add below entry in our AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

This permission is enough to access the internet by our application.

Now we need to give permission for reading and writing to our application.
These can be achieved by adding below permission in AndroidManifest.xml,

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

Now our application has full rights to read/write and access to internet.

After this configuration we need to jump in our designing part.
Here, i have used only one button download. On clicking on the download button it
simply make a remote server request to download a file.

Below is my code snippet for the screen design xml,

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<Button
        android:id="@+id/buttonDownload"
        android:text="@string/buttonDonwload"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:title="@string/buttonDonwload"/>
</menu>

After all these stuffes, now we need to code to make this apps running.
Below is the full code for which you are looking for.

---------------------------------
MainActivity.java
---------------------------------
package com.makhir.android.demo;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
private Button button;
ProgressDialog progDialog;
    int typeBar = 0;                 // Determines type progress bar: 0 = spinner, 1 = horizontal
    int delay = 40;                  // Milliseconds of delay in the update loop
    int maxBarValue = 200;           // Maximum value of horizontal progress bar
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
   
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button = (Button) findViewById(R.id.buttonDownload);

button.setOnClickListener(new View.OnClickListener() {
       @Override
            public void onClick(View v) {
                try {
                showDialog(typeBar);
String serverUrl = http://amishra.asite.asitehq.com:8080/exchange/doc.htm;
                new Downloader().getData(serverUrl);
                } catch (Exception e) {
e.printStackTrace();
}
            }
        });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

@Override
    protected Dialog onCreateDialog(int id) {
        switch(id) {
        case 0: // Spinner
            progDialog = new ProgressDialog(this);
            progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progDialog.setMessage("Downloading ...");
            progDialog.setCancelable(false);
            progDialog.show();
            return progDialog;
        case 1: // Horizontal
            progDialog = new ProgressDialog(this);
            progDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progDialog.setMax(maxBarValue);
            progDialog.setMessage("Dollars in checking account:");
            progDialog.setCancelable(false);
            progDialog.show();
            return progDialog;
        default:
            return null;
        }
    }

private class Downloader extends AsyncTask<String, String, String> {
private String reponseData = null;

@Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(typeBar);
        }

protected String doInBackground(String... args) {
int TIMEOUT_MILLISEC = 2000;
int count;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);

// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(args[0]);

try {
Log.i(getClass().getSimpleName(), "send  task - start");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
reponseData = httpclient.execute(httppost, responseHandler);
Log.i(getClass().getSimpleName(), reponseData);
InputStream inputStream = new ByteArrayInputStream(reponseData.getBytes());

FileOutputStream output = new FileOutputStream(new File("/sdcard/sampleData.xml"));
byte data[] = new byte[1024];
                long total = 0;

                while ((count = inputStream.read(data)) != -1) {
                    total += count;
                    publishProgress("" + (int)(( total * 100) / reponseData.length()));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                inputStream.close();
            } catch (Throwable t) {
t.printStackTrace();
Log.e("MainActivity", "" + t.getMessage());
}
return null;
}

protected void onProgressUpdate(String... progress) {
            Log.d("ANDRO_ASYNC",progress[0]);
            progDialog.setProgress(Integer.parseInt(progress[0]));
       }

       @Override
       protected void onPostExecute(String unused) {
           dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
  Toast.makeText(getApplicationContext(), "File downloaded successfully", Toast.LENGTH_LONG).show();
       }
 
  public String getData(String url) throws Exception{
try {
execute(url);
} catch (Exception e) {
throw e;
}
return reponseData;
}
}
}
-----

We have done all the required changes for application.
Below are the some screen snippets for application.


No comments:

Post a Comment