Monday 1 April 2013

Download video in android

//Download video in android

holder.imgDownload = (ImageView)convertView.findViewById(R.id.imgDownload);
                holder.imgDownload.setOnClickListener(new OnClickListener() {                   
                    public void onClick(View v) {
                        boolean DownloadStatus=false;
                       
                        OpenDatabase();
                          DownloadStatus=mDbHelper.SearchDuplicateDownloadVideo(mSQLiteDatabase, id,name.get(position).toString().trim());
                        CloseDataBase();
                   
                        if(DownloadStatus){
                            Toast.makeText(mContext, Html.fromHtml(Constants.DOWNLOAD.RECORD_DUPLICATE_MESSAGE),Toast.LENGTH_SHORT).show();
                        }
                        else{
                            Display display = getWindowManager().getDefaultDisplay();
                            int width = display.getWidth();
                            int height = display.getHeight();
                           
                                if(width>=800 || height>=1280)
                                {
                                    intFileName = anshd.get(position).toString().hashCode();
                                    System.out.println("strFileName=="+intFileName);
                                    mPosition = position;
                                    DownloadVideoDialog();
                                }
                                else{
                                    intFileName = ans.get(position).toString().hashCode();
                                    System.out.println("strFileName=="+intFileName);
                                    mPosition = position;
                                    DownloadVideoDialog();
                                }
                        }
                    }
                });

//******************************************************************************************************************
//    Alert dialog for download
    private void DownloadVideoDialog() {
        AlertDialog mAlertDialog = new AlertDialog.Builder(ViewGroupOrganizer.group).create();
        mAlertDialog.setTitle(Constants.DOWNLOAD.DOWNLOAD);
        mAlertDialog.setIcon(R.drawable.ic_download);
        mAlertDialog.setMessage(Constants.DOWNLOAD.DOWNLOAD_MASSAGE);
        //mAlertDialog.setCancelable(false);
        mAlertDialog.setButton(Constants.DOWNLOAD.DIALOG_BUTTON_YES, new DialogInterface.OnClickListener() {
           
            public void onClick(DialogInterface dialog, int which) {   
                //pos=position;       
                Display display = getWindowManager().getDefaultDisplay();
                int width = display.getWidth();
                int height = display.getHeight();
               
                    if(width>=800 || height>=1280)
                    {
                        Log.e("log_tag=", "device is hd.");
                        System.out.println("anshd_Download=="+anshd.get(mPosition).toString());
                        new DownloadVideo().execute(anshd.get(mPosition).toString());
                    }
                    else
                    {
                        Log.e("log_tag", "device is not hd.");
                        System.out.println("ans_Download=="+ans.get(mPosition).toString());
                        new DownloadVideo().execute(ans.get(mPosition).toString());
                    }
                }
            });
            mAlertDialog.setButton2(Constants.DOWNLOAD.DIALOG_BUTTON_NO, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        // Create and show the dialog
        mAlertDialog.show();
    }

//******************************************************************************************************************************
  //******************************************************************************************************************************
    //For Download Video file
        private int intFileName;
        private ProgressDialog mProgressDialog = null;
        int progress = 0;
        private class DownloadVideo extends AsyncTask<String,Integer, Boolean>{      
        boolean Status=false, inPostExecute = false;
        protected void onPreExecute() {
            Status = true;          
            mProgressDialog = new ProgressDialog(ViewGroupOrganizer.group);
            mProgressDialog.setCancelable(true);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setMessage(Constants.DOWNLOAD.DOWNLOADING_MESSAGE);
            mProgressDialog.setOnDismissListener(new OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                    if(inPostExecute == false){
                        Status = false;
                    }
                    if (!(DownloadVideo.this.isCancelled())) {
                        DownloadVideo.this.cancel(true);
                        if(CommanClass.MemoryCardCheck() && Status == false){
                            if(new File(Constants.PLAY_VIDEO.VIDEO_PATH + intFileName+".mp4").exists()){
                                new File(Constants.PLAY_VIDEO.VIDEO_PATH + intFileName+".mp4").delete();
                            }
                         }
                    }
                }
            });
            mProgressDialog.show();
            //For set screen orientation
            int currentOrientation = getResources().getConfiguration().orientation;
            if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
               setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
            }
            else {
               setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
            }          
            super.onPreExecute();
           }  
               protected Boolean doInBackground(String... MP3URL) {
                   if(CommanClass.MemoryCardCheck())
                   {    
                       int count;
                        try{
                                URL url = new URL(MP3URL[0]);
                                URLConnection conexion = url.openConnection();
                                conexion.connect();
                              
                                File VideoDirectory = new File(Constants.DOWNLOAD.SDCARD_VIDEO_URL);
                                   if(!VideoDirectory.exists()){
                                       VideoDirectory.mkdir();
                                   }  
                                   int lenghtOfFile = conexion.getContentLength();
                                    InputStream mInputStream=CommanClass.OpenHttpConnectionPost(MP3URL[0]);                                                                                                                   
                                    FileOutputStream fos = new FileOutputStream(VideoDirectory + "/video_" + intFileName+".mp4");
                                           byte data[] = new byte[1024];
                                           long total = 0;
                                           while ((count = mInputStream.read(data)) != -1 && Status) {
                                               total += count;
                                               publishProgress((int)((total*100)/lenghtOfFile));
                                               fos.write(data, 0, count);
                                           }
                                            fos.close();
                                            mInputStream.close();
                            }
                            catch (Exception e) {
                                   e.printStackTrace();
                                    Status=false;
                            }
                    }
                   else{
                          Status=false;
                   }
                   return Status;
               }
             
             /** This callback method is invoked when publishProgress()
                * method is called */
               @Override
               protected void onProgressUpdate(Integer... values) {
                   super.onProgressUpdate(values);
                   mProgressDialog.setProgress(values[0]);
               }
             
            protected void onPostExecute(Boolean result) {
                    if(result){
                            inPostExecute = true;
                            Toast.makeText(List.this,Html.fromHtml(Constants.DOWNLOAD.DOWNLOADING_MESSAGE), Toast.LENGTH_SHORT).show();
                          
                                if(CommanClass.isTablet(List.this))
                                {
                                    OpenDatabase();                                    
                                        mDbHelper.INSERT_DOWNLOAD_VIDEO(mSQLiteDatabase, id,name.get(mPosition).toString(),intFileName+".mp4",type.get(mPosition).toString(),imgs.get(mPosition).toString(),imgtext.get(mPosition).toString(),anshd.get(mPosition).toString());
                                    CloseDataBase();
                                }
                                else{
                                    OpenDatabase();        
                                        mDbHelper.INSERT_DOWNLOAD_VIDEO(mSQLiteDatabase, id,name.get(mPosition).toString(),intFileName+".mp4",type.get(mPosition).toString(),imgs.get(mPosition).toString(),imgtext.get(mPosition).toString(),ans.get(mPosition).toString());
                                    CloseDataBase();
                                }
                                
                    }
                    else{
                         if(CommanClass.MemoryCardCheck()){
                            if(new File(Constants.PLAY_VIDEO.VIDEO_PATH + intFileName+".mp4").exists()){
                                new File(Constants.PLAY_VIDEO.VIDEO_PATH + intFileName+".mp4").delete();
                            }
                         }
                            Toast.makeText(List.this,Html.fromHtml(Constants.DOWNLOAD.NOT_DOWNLOAD), Toast.LENGTH_SHORT).show();
                    }       
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                   mProgressDialog.dismiss();
                   super.onPostExecute(result);                      
            }    
         }
=================================================
//class DBHelper
public class DbHelper extends SQLiteOpenHelper{

    public DbHelper(Context context) {
        super(context, DBConstant.DB.DATABASENAME, null, DBConstant.DB.DB_VERSION);
    }
   
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String TABLE1 = String.format("CREATE TABLE %s (" +
                "%s INTEGER PRIMARY KEY AUTOINCREMENT," +
                "%s VARCHAR(15)," +
                "%s VARCHAR(50)," +
                "%s VARCHAR(100)," +
                "%s VARCHAR(100)," +
                "%s VARCHAR(100)," +
                "%s VARCHAR(100)," +
                "%s VARCHAR(100))", DBConstant.TABLE.VIDEODOWNLOAD,
                DBConstant.VIDEO_DOWNLOAD.VIDEO_DOWNLOAD_ID,
                DBConstant.VIDEO_DOWNLOAD.VIDEO_ID,
                DBConstant.VIDEO_DOWNLOAD.VIDEO_NAME,
                DBConstant.VIDEO_DOWNLOAD.VIDEO_FILE_NAME,
                DBConstant.VIDEO_DOWNLOAD.TYPE,
                DBConstant.VIDEO_DOWNLOAD.IMGS,
                DBConstant.VIDEO_DOWNLOAD.IMGTEXT,
                DBConstant.VIDEO_DOWNLOAD.VIDEO_DOWNLOADPATH);
       
                Log.i(Constants.TAG,"TABLE1 = " + TABLE1.toString());
                db.execSQL(TABLE1);   
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS "+ DBConstant.TABLE.VIDEODOWNLOAD);
        onCreate(db);
    }
   
    //Insert into CASH_TRANSACTION Table
    public void INSERT_DOWNLOAD_VIDEO(SQLiteDatabase db, String video_id, String video_name, String video_file_name,String type, String imgs, String imgtext, String video_path){
        ContentValues cv = new ContentValues();   
        cv.put(DBConstant.VIDEO_DOWNLOAD.VIDEO_ID,video_id);       
        cv.put(DBConstant.VIDEO_DOWNLOAD.VIDEO_NAME,video_name);
        cv.put(DBConstant.VIDEO_DOWNLOAD.VIDEO_FILE_NAME, video_file_name);
        cv.put(DBConstant.VIDEO_DOWNLOAD.TYPE,type);
        cv.put(DBConstant.VIDEO_DOWNLOAD.IMGS,imgs);
        cv.put(DBConstant.VIDEO_DOWNLOAD.IMGTEXT,imgtext);
        cv.put(DBConstant.VIDEO_DOWNLOAD.VIDEO_DOWNLOADPATH,video_path);
        db.insert(DBConstant.TABLE.VIDEODOWNLOAD, null,cv);
    }
   
    //Function for GetDownloadVideo
    public Cursor GetDownloadVideo(SQLiteDatabase db){
        return  db.query(DBConstant.TABLE.VIDEODOWNLOAD,null, null, null, null, null, null);
    }
   
    //Function for DeleteDownloadVideo
    public void DeleteDownloadVideo(SQLiteDatabase db,String video_id){
        String strwhere = String.format("%s = %s ",DBConstant.VIDEO_DOWNLOAD.VIDEO_DOWNLOAD_ID,video_id);
        db.delete(DBConstant.TABLE.VIDEODOWNLOAD, strwhere, null);
    }
   
   //*******************************************************************************************************************************   
  //Function for SearchDuplicateDownloadAudio database
    public boolean SearchDuplicateDownloadVideo(SQLiteDatabase db,String video_id,String video_name){
        String strwhere =String.format("%s = %s and %s = '%s'",DBConstant.VIDEO_DOWNLOAD.VIDEO_ID,video_id,DBConstant.VIDEO_DOWNLOAD.VIDEO_NAME,video_name);
        Cursor c =  db.query(DBConstant.TABLE.VIDEODOWNLOAD, null, strwhere, null, null, null, null);
        if(c!=null){
            if(c.getCount() > 0){
                if(!c.isClosed()){
                    c.close();
                }
                return true;
            }
            else{
                if(!c.isClosed()){
                    c.close();
                }
                return false;
            }
        }
        else{
            return false;
        }       
    }
}

No comments:

Post a Comment