0

I am trying to upload file for which I am using AsyncTask, Application is running fine until I click on upload button (which is defined in UploadActivity.java) the app stops. here is the logcat.

**Note:**I have mentioned Line numbers of given exceptions by logcat.

    FATAL EXCEPTION: AsyncTask #1 
  java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                                  at android.os.AsyncTask$3.done(AsyncTask.java:299)
                                                                                  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
                                                                                  at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
                                                                                  at java.util.concurrent.FutureTask.run(FutureTask.java:239)
                                                                                  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                                                                                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
                                                                                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
                                                                                  at java.lang.Thread.run(Thread.java:841)
                                                                               Caused by: java.lang.NoClassDefFoundError: org.apache.commons.io.output.ByteArrayOutputStream
                                                                                  at org.apache.http.entity.mime.HttpMultipart.getTotalLength(HttpMultipart.java:219)
                                                                                  at org.apache.http.entity.mime.MultipartEntity.getContentLength(MultipartEntity.java:150)
                                                                                  at com.example.imtiaz.recognizer.UploadActivity$UploadFileToServer.UploadFile(UploadActivity.java:129)
                                                                                  at com.example.imtiaz.recognizer.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:108)
                                                                                  at com.example.imtiaz.recognizer.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:90)
                                                                                  at android.os.AsyncTask$2.call(AsyncTask.java:287)
                                                                                  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
                                                                                  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
                                                                                  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
                                                                                  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
                                                                                  at java.lang.Thread.run(Thread.java:841)

Here is the UploadActivity.java code.

    public class UploadActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

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

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

        btnUpload = (Button) findViewById(R.id.btnUpload);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        imgPreview = (ImageView) findViewById(R.id.imageView);

        // Receiving the data from previous activity
        Intent i = getIntent();

        filePath = i.getStringExtra("filePath");
        // boolean flag to identify the media type,
        boolean isImage = i.getBooleanExtra("isImage", true);
        if (filePath != null) {
            // Displaying the image on the screen
            previewMedia(isImage);

        } else {
            Toast.makeText(getApplicationContext(),
                    filePath + "Sorry, file path is missing!", Toast.LENGTH_LONG).show();
        }
        //Creating EventListener.
        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 mediaType is image or not
        if (isImage) {
            imgPreview.setVisibility(View.VISIBLE);
            //Reducing image size.
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 8;
            //Bitmaping image .
            final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
            imgPreview.setImageBitmap(bitmap);

        }
    }

    //else give message media type is not image.
    private class UploadFileToServer extends AsyncTask<Void, Integer, String>//Line 90
{
        @Override
        protected void onPreExecute() {
            progressBar.setProgress(0);
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            //set view to true.
            progressBar.setVisibility(View.VISIBLE);
            //ProgressBar value.
            progressBar.setProgress(progress[0]);
        }

        @Override
        protected String doInBackground(Void... Params) {
            //do background task (UploadFile).
            return UploadFile();//Line 108
        }

        @SuppressWarnings("deprecation")
        private String UploadFile() {
            String responseString = null;
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);

            try {
                AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                        new ProgressListener() {
                            @Override
                            public void transferred(long num) {
                                publishProgress((int) (num / (float) totalSize) * 100);
                            }
                        });

                File sourceFile = new File(filePath);
                //Adding File Data to Http BOdy.
                entity.addPart("image", new FileBody(sourceFile));
                totalSize = entity.getContentLength();//Line 129
                httppost.setEntity(entity);
                //Making Server calls.
                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 Status: " + 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 Response.
            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();
    }

}

Dependencies

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.0'
compile files('libs/httpclient-4.0.jar')
compile files('libs/httpcore-4.0-alpha5.jar')
compile files('libs/apache-mime4j-0.3.jar')
compile files('libs/commons-io-2.5.jar')}
ABi
  • 143
  • 2
  • 18

2 Answers2

0

You're missing a dependency:

compile group: 'commons-io', name: 'commons-io', version: '2.5'
breakline
  • 5,776
  • 8
  • 45
  • 84
  • please post your dependencies – breakline Sep 02 '16 at 01:41
  • please check it again i have added the jar but its still saying the same – ABi Sep 02 '16 at 02:30
  • 1
    @ABi It is recommended to use Gradle dependency lines like this answer instead of JAR files. That way, transitive dependencies are also compiled into your app, then you likely won't be missing classes – OneCricketeer Sep 02 '16 at 04:48
0

You need common-io jar to over-come this problem Download it from Here

after downloading go to your project past the jar in lib folder, right click on it(commons-io.jar) and select Add as Library, That should do the trick.

ABi
  • 143
  • 2
  • 18