4

I'm following this tutorial (http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/) to uploading photo. And I'm using header authentication in httppost. But, why when uploading didn't work.

I using 'org.apache.httpcomponents:httpmime:4.3.6' in my dependencies. Anyone can help me.

This my Activity.

public class SendReportActivity extends Activity {
private static final String TAG = SendReportActivity.class.getSimpleName();

private String filePath = null;
private ImageView imgPreview;
private ProgressBar progressBar;
private TextView txtPercentage;
private Button btnUpload;
long totalSize = 0;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_send_report);

    txtPercentage = (TextView) findViewById(R.id.txtPercentage);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    btnUpload = (Button) findViewById(R.id.btnKirim);

    imgPreview = (ImageView) findViewById(R.id.imgPreview);
    Intent i = getIntent();
    filePath = i.getStringExtra("filePath");
    boolean isImage = i.getBooleanExtra("isImage", true);
    if (filePath != null) {
        // Displaying the image or video on the screen
        previewMedia(isImage);
    } else {
        Toast.makeText(getApplicationContext(),
                "Sorry, file path is missing!", Toast.LENGTH_LONG).show();
    }


    btnUpload.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // uploading the file to server
            new UploadFileToServer().execute();
        }
    });
}


private void previewMedia(boolean isImage) {
    // Checking whether captured media is image or video
    if (isImage) {
        imgPreview.setVisibility(View.VISIBLE);
        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // down sizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;

        final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

        imgPreview.setImageBitmap(bitmap);
    }
}


private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
    @Override
    protected void onPreExecute() {
        // setting progress bar to zero
        progressBar.setProgress(0);
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        // Making progress bar visible
        progressBar.setVisibility(View.VISIBLE);

        // updating progress bar value
        progressBar.setProgress(progress[0]);

        // updating percentage value
        txtPercentage.setText(String.valueOf(progress[0]) + "%");
    }

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

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

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(AppConfig.URL_LAPOR);
        httppost.addHeader("Authorization", "Basic " +
                Base64.encodeToString((AppConfig.USER_API + ":" + AppConfig.PASSWORD_API).getBytes(), Base64.DEFAULT));

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

                        @Override
                        public void transferred(long num) {
                            publishProgress((int) ((num / (float) totalSize) * 100));
                        }
                    });

            File sourceFile = new File(filePath);

            entity.addPart("data_des", new StringBody("OK"));
            entity.addPart("data_upload", new FileBody(sourceFile));

            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);
            } else {
                responseString = "Error occurred! Http Status Code: "
                        + statusCode;
            }

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

        return responseString;

    }

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

        // showing the server response in an alert dialog
        showAlert(result);

        super.onPostExecute(result);
    }

}


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();
}
}

This error log.

FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:278)
        at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
        at java.util.concurrent.FutureTask.run(FutureTask.java:137)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
        at java.lang.Thread.run(Thread.java:856)
 Caused by: java.lang.NoClassDefFoundError: org.apache.http.Consts
        at org.apache.http.entity.mime.content.StringBody.<init>(StringBody.java:148)
        at com.company.report.activity.SendReportActivity$UploadFileToServer.uploadFile(SendReportActivity.java:232)
        at com.company.report.activity.SendReportActivity$UploadFileToServer.doInBackground(SendReportActivity.java:208)
        at com.company.report.activity.SendReportActivity$UploadFileToServer.doInBackground(SendReportActivity.java:186)
        at android.os.AsyncTask$2.call(AsyncTask.java:264)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
 at java.util.concurrent.FutureTask.run(FutureTask.java:137)
 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
user3089464
  • 251
  • 6
  • 14
  • You can see [my answer here](http://stackoverflow.com/questions/16797468/how-to-send-a-multipart-form-data-post-in-android-with-volley/31718902#31718902) – BNK Sep 10 '15 at 08:35
  • Thanks @BNK, but i have new problem. I have open new question. http://stackoverflow.com/questions/32513457/how-to-send-a-multipart-request-in-android-with-volley. Can you help me please.. – user3089464 Sep 11 '15 at 00:05

0 Answers0