0

I made a program which uploads selected videos from the SD card to an ASP.NET server. Now I want to add a progress bar to show the status of the uploading file? Can anyone help me about this issue? I am a bit confused. I tried many ways to display the status but I was not successful.

Thanks for helping.

package com.isoft.uploder;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ParseException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button; 
import android.widget.ProgressBar;

public class VideoUploader extends Activity 
{
  /** Called when the activity is first created. */

public static final int SELECT_VIDEO=1;
public static final String TAG="UploadActivity";
String path="";

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button camera =(Button)findViewById(R.id.camera);
    Button back= (Button)findViewById(R.id.back1);
    Button select=(Button)findViewById(R.id.select);
    //Video Çek
    camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivity(intent);
        }
    });
    //
    //Video Seç
    select.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            openGaleryVideo();
        }
    });
    //
    //Geri Dön
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            finish();
        }
    });
    //
}

//Gallery'i aç
public void openGaleryVideo()
{
    Intent intent=new Intent();
    intent.setType("video/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Video"),SELECT_VIDEO);
}

//Dosyayı seç ve yükle
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_VIDEO) {
            Uri videoUri = data.getData();
            path= getPath(videoUri);
            doFileUpload();
        }
    }
}

//SD carddan yerini al
public String getPath(Uri uri)
{   
    String[] projection = { MediaStore.Video.Media.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

//upload et
public void doFileUpload()
{   
        File file=new File(path);  
        String urlServer = "http://192.168.10.177/androidweb/default.aspx";
        String filename=file.getName();
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 10*1024*1024;
        try
        {
        FileInputStream fileInputStream = new FileInputStream(file);
        URL url = new URL(urlServer);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setFixedLengthStreamingMode((int) file.length());

        // Allow Inputs & Outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // Enable POST method
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type",  "multipart/form-data");
        connection.setRequestProperty("SD-FileName", filename);//This will be the file name
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // Read file
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0)
        {   
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }//end of while statement


            //Tekrar video seçmek için
            setContentView(R.layout.end);
            //event
            Button back2=(Button)findViewById(R.id.back2);
            Button select2=(Button)findViewById(R.id.new1);
            back2.setOnClickListener(new View.OnClickListener() 
            {
                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    finish();
                }
            });
            select2.setOnClickListener(new View.OnClickListener() 
            {
                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    openGaleryVideo();
                }
            });
            //

         //int serverResponseCode = connection.getResponseCode();
         //String serverResponseMessage = connection.getResponseMessage();
         //Log.d("ServerCode",""+serverResponseCode);
         //Log.d("serverResponseMessage",""+serverResponseMessage);
         fileInputStream.close();
         outputStream.flush();
         outputStream.close();
        }//end of try body

        catch (Exception ex)
        {
            //ex.printStackTrace();
            Log.e("Error: ", ex.getMessage());
        }
      }
  }
answer88
  • 165
  • 7
  • 19

2 Answers2

0

I did same kind of work, have a look at to my code,

public class LogUploaderActivity extends Activity 
{
    private static LogUploaderActivity thisAct = null;
    private ButtonListener buttonClickListener = null;
    private MyDialogInterfaceListener dListener = null;

    private RadioButton rbServer;
    private RadioButton rbEmail;

    private Button cmdOK;
    private Button cmdCancel;

    // Progress Bar Variables
    private static AlertDialog alertDialog = null;
    private static ProgressDialog progressDialog = null;

    private int delay = 1000;    
    private ProgressThread progThread;
    private int maxBarValue;

    private String[] fileName;

    private static File directory = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        thisAct = this;

//        directory = Environment.getExternalStorageDirectory();

        rbServer = (RadioButton) findViewById( R.id.rdWebServer );
        rbEmail = (RadioButton) findViewById( R.id.rdLTLogs );

        cmdOK = (Button) findViewById( R.id.cmdOK );
        cmdCancel = (Button) findViewById( R.id.cmdCancel );

        cmdOK.setOnClickListener(getListener());
        cmdCancel.setOnClickListener(getListener());

    }

    private int readLogList( String filePath )
    {
        directory = Environment.getExternalStorageDirectory();

//      System.out.println ( directory + ConstantCodes.FILE_SEPARATOR + filePath );

        File folder = new File( directory + ConstantCodes.FILE_SEPARATOR + filePath );

        if ( !folder.exists() )
        {
            return 0;
        }

        fileName = folder.list();

        return  folder.list().length;
    }

    private String readSingleFile( String filePath, String fileName )
    {
        try
        {
//          File directory = Environment.getExternalStorageDirectory();

//          System.out.println ( "Dir : " + directory );

            System.gc();

            File file = new File ( directory + ConstantCodes.FILE_SEPARATOR + filePath , fileName );

            BufferedReader br = new BufferedReader ( new FileReader ( file) );
            String line;
            StringBuffer sb = new StringBuffer();

            while ( ( line = br.readLine() ) != null )
            {
                sb.append(line);
            }

//          byte[] fileData = sb.toString().trim().getBytes();

//          String content = sb.toString().trim();

            System.out.println ( "File Size : " + sb.toString().length() );

            return sb.toString().trim();
        }
        catch ( Exception e )
        {
            System.out.println ( "Error while reading File " + e.toString() );
            return null;
        }
    }

    private MyDialogInterfaceListener getDialogListener()
    {
        if ( dListener == null )
        {
            dListener = new MyDialogInterfaceListener();
        }
        return dListener;
    }

    private ButtonListener getListener()
    {
        if ( buttonClickListener == null )
        {
            buttonClickListener = new ButtonListener();
        }
        return buttonClickListener;
    }

    private class MyDialogInterfaceListener implements DialogInterface.OnClickListener
    {
        public void onClick(DialogInterface dialog, int which)
        {
            alertDialog.dismiss();
        }
    }

    private class ButtonListener implements Button.OnClickListener
    {
        public void onClick ( View view )
        {
            if ( view == cmdCancel )
            {
                finish();
            }
            else if ( view == cmdOK )
            {
                // First Check which Radio Button is selected 
                if ( rbServer.isChecked() )
                {
                    try
                    {
                        maxBarValue = readLogList( ConstantCodes.APPLICATION_LOG_PATH );
                        Thread.sleep(1000);
                    }
                    catch ( Exception e ) { }

                    if ( maxBarValue > 0 )
                    {
                        progressDialog = new ProgressDialog ( thisAct );
                        progressDialog.setProgressStyle( ProgressDialog.STYLE_HORIZONTAL );
                        progressDialog.setMax(maxBarValue);
                        progressDialog.setMessage( "Uploading Files" );
                        progressDialog.show();

                        progThread = new ProgressThread( handler, ConstantCodes.APPLICATION_LOG_PATH, ConstantCodes.TEXT_FILE_METHOD_NAME );
                        progThread.start();
                    }
                    else
                    {
                        alertDialog = new AlertDialog.Builder(thisAct).create();
                        alertDialog.setTitle( "Error" );
                        alertDialog.setMessage( "No More Logs to Upload" );
                        alertDialog.setButton( "OK", getDialogListener());
                        alertDialog.show();
                    }
                }
                else if ( rbEmail.isChecked() )
                {
                    try
                    {
                        maxBarValue = readLogList( ConstantCodes.LOCATION_TRACKER_PATH );
                        Thread.sleep(1000);
                    }
                    catch ( Exception e ) { }

                    if ( maxBarValue > 0 )
                    {
                        progressDialog = new ProgressDialog ( thisAct );
                        progressDialog.setProgressStyle( ProgressDialog.STYLE_HORIZONTAL );
                        progressDialog.setMax(maxBarValue);
                        progressDialog.setMessage( "Uploading Files" );
                        progressDialog.show();
                    }
                    else
                    {
                        alertDialog = new AlertDialog.Builder(thisAct).create();
                        alertDialog.setTitle( "Error" );
                        alertDialog.setMessage( "No More Logs to Upload" );
                        alertDialog.setButton( "OK", getDialogListener());
                        alertDialog.show();
                    }

                    progThread = new ProgressThread( handler,ConstantCodes.LOCATION_TRACKER_PATH, ConstantCodes.LOCATION_TRACKER_METHOD_NAME );
                    progThread.start();
                }
                else
                {
                    alertDialog = new AlertDialog.Builder(thisAct).create();
                    alertDialog.setTitle( "Error" );
                    alertDialog.setMessage( "Please Select Any One Option" );
                    alertDialog.setButton( "OK", getDialogListener());
                    alertDialog.show();
                }
            }   
        }
    }

    final Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            int total = msg.getData().getInt("total");  
            progressDialog.setProgress(total);
            if (total >= maxBarValue)
            {
                progressDialog.dismiss();
                progThread.setState(ProgressThread.DONE);
            }
        }
    };


    private class ProgressThread extends Thread
    {
        final static int DONE = 0;
        final static int RUNNING = 1; 
        int status;
        int total;
        String filePath;
        String METHOD_NAME;

        Handler mHandler;

        ProgressThread(Handler h, String filePath,String METHOD_NAME ) 
        {
            mHandler = h;
            this.filePath = filePath;
            this.METHOD_NAME = METHOD_NAME;
        }

        @Override
        public void run()
        {
            status = RUNNING;
            while ( status == RUNNING )
            {
                try
                {
                    Thread.sleep(delay);
                }
                catch ( Exception e ) { }

                Message msg = mHandler.obtainMessage();
                Bundle b = new Bundle();
                b.putInt("total", total);
                msg.setData(b);
                mHandler.sendMessage(msg);

//              if ( total < fileName.length )
                {
//                  System.out.println ( "Uploading File Name : " + fileName[total] );

                    try
                    {

//                      System.out.println ( "Method Name : " + METHOD_NAME );

                        int response = WebService.fileUpload( METHOD_NAME, fileName[total], readSingleFile( filePath,fileName[total] ) );

                        System.out.println ( "response  " + response );

                        if ( response == 404 )
                        {
                            progressDialog.dismiss();
                            setState(ProgressThread.DONE);

//                          Thread.sleep(500);
//                          
//                          alertDialog = new AlertDialog.Builder( getActivity() ).create();
//                          alertDialog.setTitle( "Error" );
//                          alertDialog.setMessage( "Error While Uploading" );
////                            alertDialog.setButton( "OK", getDialogListener());
//                          alertDialog.show();
                        }
                    }
                    catch ( Exception e )
                    {
//                      alertDialog = new AlertDialog.Builder( thisAct ).create();
//                      alertDialog.setTitle( "Error" );
//                      alertDialog.setMessage( "Error While Uploading" );
//                      alertDialog.setButton( "OK", getDialogListener());
//                      alertDialog.show();
                    }
                }
                total++;
            }
        }

        public void setState(int state) 
        {
            status = state;
        }
    }

    public static LogUploaderActivity getActivity()
    {
        return thisAct;
    }

    public void onDestroy() 
    {
        super.onDestroy();
    }
}

It displays total number of files in the sd cards and uploads them to server one by one and shows the status as 2/20 is uploading in progress dialogbox.

Lucifer
  • 29,392
  • 25
  • 90
  • 143
  • @Lucifeer Thanks for your response but I want to add this bar to show the percentage of the uploaded file in real time. Do you have any suggestion. I will post my code here. – answer88 Jun 26 '12 at 08:42
  • @answer88 ok, post your code, it might help me to guide you more :) – Lucifer Jun 26 '12 at 08:43
  • @answer88 : use AsynTask for downloading data from server and use onProgressUpdate to update progress bar according to downloaded data from server – ρяσѕρєя K Jun 26 '12 at 08:44
  • @imrankhan I want to upload a file to a server I dont want to download a file from the server. – answer88 Jun 26 '12 at 08:48
  • @answer88 : it's ok but you can use AsynTask easily for showing Progressbar. – ρяσѕρєя K Jun 26 '12 at 08:50
  • @Lucifer I edited my question and my code is in the question right now :) – answer88 Jun 26 '12 at 08:57
  • @answer88 i saw your code, i can only give you hint, you need to do like my code and display the %age in progress bar , the part you have uploaded to the server for a particular file. – Lucifer Jun 26 '12 at 08:59
  • @Lucifer Do you suggest me to put a similar code into the doUploadFile() method? Or Should I put the progress after closing the inputstreaming? – answer88 Jun 26 '12 at 10:19
  • @imrankhan could you please help how to put my code into asyncTask to show progress bar? Do I need to put the whole code into a asyncTask or only the uploadFile() method? – answer88 Jul 02 '12 at 11:56
  • @answer88 : yes you just call uploadFile() in asyncTask but first remove all UI elements from uploadFile() – ρяσѕρєя K Jul 02 '12 at 12:08
  • @imrankhan sorry but I am a bit confused. I have a method called "doFileUpload()" and I need to call this method after getting the uri of the file. How can I solve this problem and make an AsnycTask? By the way why should I remove all UI elements? – answer88 Jul 02 '12 at 12:26
0

If you intend a progress bar in the notification area, please refer to my answer in: Android: show notification bar on downloading application

Community
  • 1
  • 1
Nermeen
  • 15,883
  • 5
  • 59
  • 72