How to Upload Image and video on server

  • Replies:0
Vinod Takhar
  • Forum posts: 1

Feb 7, 2017, 8:10:05 AM via Website

package com.application.talendia.Activities.View;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;

import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;

import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.application.talendia.Activities.Utils.AndroidMultiPartEntity;
import com.application.talendia.Activities.Utils.Config;
import com.application.talendia.Activities.Utils.RequestHandler;
import com.application.talendia.Activities.WebServices.ApiWebInterface;
import com.application.talendia.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

public class MoreAbout extends AppCompatActivity {
Button btnNext;
ImageButton btnBack;
RelativeLayout btnVideoUpload, btnUploadAwards;
String mSubmittedID = "", mUser_ID = "";
private Uri mImageCaptureUri;
private Uri fileUri; // file url to store image/video
ImageView mImageProfile, btnCamera;
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_FILE = 2;
private static final int CAMERA_CAPTURE_IMAGE_UPLOAD = 3;
private static final int GALLERY_SELECT_IMAGE_UPLOAD = 4;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 5;
private static final int GALLERY_SELECT_VIDEO_REQUEST_CODE = 6;
Bitmap mAwardBitmap = null;
int mChooserAction = 0;

public static final int MEDIA_TYPE_IMAGE = 10;
public static final int MEDIA_TYPE_VIDEO = 20;
boolean isImage = false, isImageCapture = false;

SharedPreferences pref;
String mAwardName = "", mAwardInfo = "";
String mVideoName = "", mVideoInfo = "", mVideoTag = "", mVideoTitle = "";
EditText edTalentName, edTalentDis, edPotentialBenefits, edPotentialBuyer;
String mTalentName, mTalentDis, mPotentialBenefits, mPotentialBuyer;
ProgressDialog progressDialog=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initView();
    getSharePreferenceData();
    getBundleIntent();
    buttonClickListener();
}

private void getSharePreferenceData() {
    pref = getSharedPreferences("Telndia", MODE_PRIVATE);
    mUser_ID = pref.getString("USER_ID", "");
}

private void getBundleIntent() {
    Bundle intentData = getIntent().getExtras();
    if (intentData != null) {
        mSubmittedID = intentData.getString("SUB_ID");
        Log.e("Intent From Last", mSubmittedID);
    }
}

private void initView() {
    setContentView(R.layout.activity_more_about);
    btnCamera = (ImageView) findViewById(R.id.img_camera);// btnCAMERA
    mImageProfile = (ImageView) findViewById(R.id.imageView1);//imageview Profile
    btnVideoUpload = (RelativeLayout) findViewById(R.id.btn_video);
    btnUploadAwards = (RelativeLayout) findViewById(R.id.btn_award);
    btnNext = (Button) findViewById(R.id.btn_nextmore);
    btnBack = (ImageButton) findViewById(R.id.btn_backmore);

    edTalentName = (EditText) findViewById(R.id.editTextTalentName);
    edTalentDis = (EditText) findViewById(R.id.editTextTalentDis);
    edPotentialBenefits = (EditText) findViewById(R.id.editTextPBenifits);
    edPotentialBuyer = (EditText) findViewById(R.id.editTextPBuyers);

}


private void buttonClickListener() {
    // Open Action chooser dialog for select Image
    btnCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.e("click", "yes");
            mChooserAction = 1;
            imageChooser();
        }
    });

    // Go back on previous activity
    btnBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intenmore = new Intent(MoreAbout.this, Select_Categories.class);
            startActivity(intenmore);
        }
    });

    // Submit data using web API
    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          /*  Intent intent = new Intent(MoreAbout.this, Complete_profile.class);
            startActivity(intent);*/
            mTalentName = edTalentName.getText().toString().trim();
            mTalentDis = edTalentDis.getText().toString().trim();
            mPotentialBenefits = edPotentialBenefits.getText().toString().trim();
            mPotentialBuyer = edPotentialBuyer.getText().toString().trim();

            if (mTalentName.equals("")) {
                edTalentName.setError("required field");
            } else if (mTalentDis.equals("")) {
                edTalentDis.setError("required field");
            } else if (mPotentialBenefits.equals("")) {
                edPotentialBenefits.setError("required field");
            } else if (mPotentialBuyer.equals("")) {
                edPotentialBuyer.setError("required field");
            } else {
                Log.e("Permission", "success");
                new UploadProfileToServer().execute();
            }
           /* else if (!isImageCapture) {
                Toast.makeText(MoreAbout.this, "Please select a profile image", Toast.LENGTH_LONG).show();
            }*/

        }
    });


    btnUploadAwards.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialogAward();
        }
    });
    btnVideoUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialogVideo();
        }
    });
}

/*
* Image Chooser from Camera or Gallery
* */

/* public void imageChooser() {
final Dialog dialog = new Dialog(MoreAbout.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_image_chooser);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
RelativeLayout btnCamera = (RelativeLayout) dialog.findViewById(R.id.buttonCamera);
RelativeLayout btnGallery = (RelativeLayout) dialog.findViewById(R.id.buttonGallery);
final ImageView mImageView = (ImageView) dialog.findViewById(R.id.imageViewClose);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
btnCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
mImageCaptureUri = Uri.fromFile(file);

            try {
                intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
                intent.putExtra("return-data", true);
                startActivityForResult(intent, PICK_FROM_CAMERA);
            } catch (Exception e) {
                e.printStackTrace();
            }
            dialog.dismiss();
        }
    });
    btnGallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("image*//*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
            dialog.dismiss();
        }
    });
    dialog.show();

}*/


public void imageChooser() {
    final Dialog dialog = new Dialog(MoreAbout.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.dialog_image_chooser);
    dialog.setCancelable(true);
    dialog.setCanceledOnTouchOutside(true);
    RelativeLayout btnCamera = (RelativeLayout) dialog.findViewById(R.id.buttonCamera);
    RelativeLayout btnGallery = (RelativeLayout) dialog.findViewById(R.id.buttonGallery);
    final ImageView mImageView = (ImageView) dialog.findViewById(R.id.imageViewClose);
    mImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    btnCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mChooserAction == 1) {
                Log.e("For profile camera", "chooser=1");
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                mImageCaptureUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
                startActivityForResult(intent, PICK_FROM_CAMERA);
                mChooserAction = 0;

            } else {
                Log.e("For award camera", "chooser=0");
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_UPLOAD);
            }
            dialog.dismiss();
        }
    });
    btnGallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mChooserAction == 1) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
                mChooserAction = 0;
                dialog.dismiss();


            } else {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Complete action using"), GALLERY_SELECT_IMAGE_UPLOAD);
                dialog.dismiss();
            }


        }
    });
    dialog.show();

}

/*
* For choose video from camera or Gallery
* */
public void videoChooser() {
    final Dialog dialog = new Dialog(MoreAbout.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.dialog_image_chooser);
    dialog.setCancelable(true);
    dialog.setCanceledOnTouchOutside(true);
    RelativeLayout btnCamera = (RelativeLayout) dialog.findViewById(R.id.buttonCamera);
    RelativeLayout btnGallery = (RelativeLayout) dialog.findViewById(R.id.buttonGallery);
    final ImageView mImageView = (ImageView) dialog.findViewById(R.id.imageViewClose);
    mImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    btnCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Log.e("For video camera", "chooser=0");
            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
            fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
            // set video quality
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
            // start the video capture Intent
            startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);

            dialog.dismiss();
        }
    });
    btnGallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("video/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select a video"), GALLERY_SELECT_VIDEO_REQUEST_CODE);
            dialog.dismiss();
        }


    });
    dialog.show();

}


/**
 * Here we store the file url as it will be null after returning from camera
 * app
 */
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // save file url in bundle as it will be null on screen orientation
    // changes
    outState.putParcelable("file_uri", fileUri);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    // get the file url
    fileUri = savedInstanceState.getParcelable("file_uri");
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) return;
    Bitmap bitmap = null;
    String path = "";

    if (requestCode == PICK_FROM_FILE) {//           select image for Profile from Gallery
        //Profile Pic from Gallery
        mImageCaptureUri = data.getData();
        path = getRealPathFromURI(mImageCaptureUri); //from Gallery
        if (path == null)
            path = mImageCaptureUri.getPath(); //from File Manager
        if (path != null)
            bitmap = BitmapFactory.decodeFile(path);

        mImageProfile.setImageBitmap(bitmap);
    } else if (requestCode == PICK_FROM_CAMERA) {//           select image for Profile from Camera
        // Profile Pic from Camera
        if (resultCode == RESULT_OK) {
            Log.e("isImageCapture", "true");
            path = mImageCaptureUri.getPath();
            bitmap = BitmapFactory.decodeFile(path);
            mImageProfile.setImageBitmap(bitmap);
            isImageCapture = true;
        } else if (resultCode == RESULT_CANCELED) {
            Log.e("isImageCapture", "cancel");
            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Log.e("isImageCapture", "failed");
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }
    } else if (requestCode == CAMERA_CAPTURE_IMAGE_UPLOAD) {//            select Image for Upload from Camera
        if (resultCode == RESULT_OK) {
            Log.e("is image", "true");
            isImage = true;
        } else if (resultCode == RESULT_CANCELED) {
            Log.e("is image", "cancel");
            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Log.e("is image", "failed");
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }

    } else if (requestCode == GALLERY_SELECT_IMAGE_UPLOAD) {//            select image for Upload from Gallery
        if (resultCode == RESULT_OK) {
            Log.e("is image", " Gallery true");
            fileUri = data.getData();
            isImage = true;
        } else if (resultCode == RESULT_CANCELED) {
            Log.e("is image", "cancel");
            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Log.e("is image", "failed");
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }

    } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {//            record video for Upload from Camera


        if (resultCode == RESULT_OK) {
            // video successfully recorded
            isImage = true;

        } else if (resultCode == RESULT_CANCELED) {
            // user cancelled recording
            Toast.makeText(getApplicationContext(),
                    "User cancelled video recording", Toast.LENGTH_SHORT)
                    .show();

        } else {
            // failed to record video
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                    .show();
        }
    } else if (requestCode == GALLERY_SELECT_VIDEO_REQUEST_CODE) {//            select video for Upload from Gallery
        if (resultCode == RESULT_OK) {
            Log.e("is image", " Gallery true");
            fileUri = data.getData();
            isImage = true;
        } else if (resultCode == RESULT_CANCELED) {
            Log.e("is image", "cancel");
            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Log.e("is image", "failed");
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }

    }

}

public String getRealPathFromURI(Uri contentUri) {
    String[] proj = {MediaStore.Images.Media.DATA};
    Cursor cursor = managedQuery(contentUri, proj, null, null, null);
    if (cursor == null) return null;
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

public void dialogAward() {
    final Dialog dialog = new Dialog(MoreAbout.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.award_popup);
    dialog.setCancelable(true);
    dialog.setCanceledOnTouchOutside(true);
    final EditText edAwardName = (EditText) dialog.findViewById(R.id.editAwardName);
    final EditText edAwardInfo = (EditText) dialog.findViewById(R.id.editAwardInfo);
    Button btnSubmitAward = (Button) dialog.findViewById(R.id.btn_submitAward);
    Button btnAwardUpload = (Button) dialog.findViewById(R.id.btn_awardUpload);
    btnAwardUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageChooser();
        }
    });

    btnSubmitAward.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mAwardName = edAwardName.getText().toString().trim();
            mAwardInfo = edAwardInfo.getText().toString().trim();
            if (mAwardName.equals("")) {
                edAwardName.setError("required field");
            } else if (mAwardInfo.equals("")) {
                edAwardInfo.setError("required field");
            } else if (!isImage) {
                Toast.makeText(MoreAbout.this, "Please select a award", Toast.LENGTH_LONG).show();
            } else {
                Log.e("Permission", "success");
                new UploadFileToServer().execute();
                dialog.dismiss();
            }
        }
    });
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.show();
}

/**
 * Creating file uri to store image/video
 */
public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

/**
 * returning image / video
 */
private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            Config.IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("File", "Oops! Failed create "
                    + Config.IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "VID_" + timeStamp + ".mp4");
    } else {
        return null;
    }

    return mediaFile;
}


//    Checking device has camera hardware or not
private boolean isDeviceSupportCamera() {
    if (getApplicationContext().getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_CAMERA)) {
        // this device has a camera
        return true;
    } else {
        // no camera on this device
        return false;
    }
}


public void dialogVideo() {
    final Dialog dialog = new Dialog(MoreAbout.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.video_popup);
    dialog.setCancelable(true);
    dialog.setCanceledOnTouchOutside(true);
    final EditText edVideoTitle = (EditText) dialog.findViewById(R.id.video_title);
    final EditText edVideoName = (EditText) dialog.findViewById(R.id.video_name);
    final EditText edVideoTag = (EditText) dialog.findViewById(R.id.video_tag);
    final EditText edVideoInfo = (EditText) dialog.findViewById(R.id.video_info);
    Button btnVideoSelect = (Button) dialog.findViewById(R.id.btn_videopopup);
    Button btnVideoSubmit = (Button) dialog.findViewById(R.id.btn_submitVideo);
    btnVideoSelect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            videoChooser();
        }
    });
    btnVideoSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mVideoTitle = edVideoTitle.getText().toString().trim();
            mVideoName = edVideoName.getText().toString().trim();
            mVideoTag = edVideoTag.getText().toString().trim();
            mVideoInfo = edVideoInfo.getText().toString().trim();
            if (mVideoTitle.equals("")) {
                edVideoTitle.setError("required field");
            } else if (mVideoName.equals("")) {
                edVideoName.setError("required field");
            } else if (mVideoTag.equals("")) {
                edVideoTag.setError("required field");
            } else if (mVideoInfo.equals("")) {
                edVideoInfo.setError("required field");
            } else if (!isImage) {
                Toast.makeText(MoreAbout.this, "Please select a video", Toast.LENGTH_LONG).show();
            } else {
                Log.e("Permission video", "success");
                new UploadVideoToServer().execute();
                dialog.dismiss();
            }

        }
    });


    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.show();


}

/**
 * Uploading the image to server Awards
 */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
    @Override
    protected void onPreExecute() {
        // setting progress bar to zero
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {

    }

    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    @SuppressWarnings("deprecation")
    private String uploadFile() {
        String responseString = null;

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(ApiWebInterface.BASE_URL + "uploadAward");

        try {
            AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                    new AndroidMultiPartEntity.ProgressListener() {

                        @Override
                        public void transferred(long num) {

// publishProgress((int) ((num / (float) totalSize) * 100));
}
});

            File sourceFile = new File(fileUri.getPath());

            // Adding file data to http body
            entity.addPart("awardImage", new FileBody(sourceFile));
            // Extra parameters if you want to pass to server
            entity.addPart("userId", new StringBody(mUser_ID));
            entity.addPart("awardName", new StringBody(mAwardName));
            entity.addPart("awardInfo", new StringBody(mAwardInfo));
            entity.addPart("talentId", new StringBody(mSubmittedID));

// totalSize = entity.getContentLength();
httppost.setEntity(entity);

            // Making server call
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // Server response
                responseString = EntityUtils.toString(r_entity);
                try {
                    JSONObject obj = new JSONObject(responseString);
                    JSONObject res = obj.getJSONObject("response");
                    String mStatus = res.getString("status");
                    Log.e("Json status", mStatus);
                    if (mStatus.equalsIgnoreCase("1")) {
                        Toast.makeText(MoreAbout.this, "Award Uploaded", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } else {
                responseString = "Error occurred! Http Status Code: "
                        + statusCode;
                Toast.makeText(MoreAbout.this, responseString, Toast.LENGTH_SHORT).show();
            }

        } catch (ClientProtocolException e) {
            responseString = e.toString();
        } catch (IOException e) {
            responseString = e.toString();
        }

        return responseString;

    }

    @Override
    protected void onPostExecute(String result) {
        Log.e("Response for Award", "Response from server: " + result);

        // showing the server response in an alert dialog

// showAlert(result);

        super.onPostExecute(result);
    }

}


/**
 * Uploading the Profile to server
 */
private class UploadProfileToServer extends AsyncTask<Void, Integer, String> {


    @Override
    protected void onPreExecute() {
        // setting progress bar to zero

// progressDialog = ProgressDialog.show(MoreAbout.this, "", "Please wait...");
super.onPreExecute();
}

    @Override
    protected void onProgressUpdate(Integer... progress) {

    }

    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    @SuppressWarnings("deprecation")
    private String uploadFile() {
        String responseString = null;

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(ApiWebInterface.BASE_URL + "uploadProfile");

        try {
            AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                    new AndroidMultiPartEntity.ProgressListener() {

                        @Override
                        public void transferred(long num) {

// publishProgress((int) ((num / (float) totalSize) * 100));
}
});

            File sourceFile = new File(mImageCaptureUri.getPath());

            // Adding file data to http body
            entity.addPart("profileImage", new FileBody(sourceFile));
            // Extra parameters if you want to pass to server
            entity.addPart("userId", new StringBody(mUser_ID));
            entity.addPart("talentName", new StringBody(mTalentName));
            entity.addPart("talentDescription", new StringBody(mTalentDis));
            entity.addPart("talentId", new StringBody(mSubmittedID));

// totalSize = entity.getContentLength();
httppost.setEntity(entity);

            // Making server call
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // Server response
                responseString = EntityUtils.toString(r_entity);
                try {
                    JSONObject obj = new JSONObject(responseString);
                    JSONObject res = obj.getJSONObject("response");
                    String mStatus = res.getString("status");
                    Log.e("Json status", mStatus);
                    if (mStatus.equalsIgnoreCase("1")) {

// Toast.makeText(MoreAbout.this, "Profile Uploaded", Toast.LENGTH_SHORT).show();
Intent mIntent = new Intent(MoreAbout.this, Complete_profile.class);
mIntent.putExtra("SUB_ID",mSubmittedID);
startActivity(mIntent);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
Toast.makeText(MoreAbout.this, responseString, Toast.LENGTH_SHORT).show();
}

        } catch (ClientProtocolException e) {
            responseString = e.toString();
        } catch (IOException e) {
            responseString = e.toString();
        }

        return responseString;

    }

    @Override
    protected void onPostExecute(String result) {
        Log.e("Response for Profile", "Response from server: " + result);

        // showing the server response in an alert dialog

// showAlert(result);
// progressDialog.dismiss();
super.onPostExecute(result);
}

}


/**
 * Uploading the image to server Awards
 */
private class UploadVideoToServer extends AsyncTask<Void, Integer, String> {
    @Override
    protected void onPreExecute() {
        // setting progress bar to zero
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {

    }

    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    @SuppressWarnings("deprecation")
    private String uploadFile() {
        String responseString = null;

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(ApiWebInterface.BASE_URL + "uploadVideo");

        try {
            AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                    new AndroidMultiPartEntity.ProgressListener() {

                        @Override
                        public void transferred(long num) {

// publishProgress((int) ((num / (float) totalSize) * 100));
}
});

            File sourceFile = new File(fileUri.getPath());

            // Adding file data to http body
            entity.addPart("talentVideo", new FileBody(sourceFile));
            // Extra parameters if you want to pass to server
            entity.addPart("userId", new StringBody(mUser_ID));
            entity.addPart("talentId", new StringBody(mSubmittedID));
            entity.addPart("video_tittle", new StringBody(mVideoTitle));
            entity.addPart("video_name", new StringBody(mVideoName));
            entity.addPart("video_info", new StringBody(mVideoInfo));
            entity.addPart("videoTag", new StringBody(mVideoTag));

// totalSize = entity.getContentLength();
httppost.setEntity(entity);

            // Making server call
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // Server response
                responseString = EntityUtils.toString(r_entity);
                try {
                    JSONObject obj = new JSONObject(responseString);
                    JSONObject res = obj.getJSONObject("response");
                    String mStatus = res.getString("status");
                    Log.e("Json status", mStatus);
                    if (mStatus.equalsIgnoreCase("1")) {
                        Toast.makeText(MoreAbout.this, "Video Uploaded", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            } else {
                responseString = "Error occurred! Http Status Code: "
                        + statusCode;
                Toast.makeText(MoreAbout.this, responseString, Toast.LENGTH_SHORT).show();
            }


        } catch (ClientProtocolException e) {
            responseString = e.toString();
        } catch (IOException e) {
            responseString = e.toString();
        }

        return responseString;

    }

    @Override
    protected void onPostExecute(String result) {
        Log.e("Response for video", "Response from server: " + result);

        // showing the server response in an alert dialog

// showAlert(result);

        super.onPostExecute(result);
    }

}


/**
 * Method to show alert dialog
 */
private void showAlert(String message) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(message).setTitle("Response from Servers")
            .setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // do nothing
                }
            });
    AlertDialog alert = builder.create();
    alert.show();
}

}

By Vinod Takhar

Reply