2

i am currently making an app to get the image from the camera and the gallery to upload to the PHP server. But there is something wrong with my app. I used two ways to do this task. The first one is to encode the image with Base64, then use the UrlEncodedFormEntity in the httppost. It worked. Then i used the MultiPartEntityBuilder. When i pressed the upload button, the app stopped. Can someone helped me out? My code is as below, it is a little messy. Sorry about that.

package com.ascc.cloud;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;




import java.io.ByteArrayOutputStream;
import java.util.ArrayList;


public class MainActivity extends Activity {

Button btpic, btnup, btgal;
private Uri fileUri;
String picturePath=null;
Uri selectedImage;
Bitmap photo;
String ba1;
public static String URL = "http://139.78.78.187/store.php";
public static int RESULT_LOAD_IMG=1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btpic = (Button) findViewById(R.id.cpic);
    btpic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            clickpic();
        }
    });

    btnup = (Button) findViewById(R.id.up);
    btnup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            upload();
        }
    });

    btgal=(Button) findViewById(R.id.gallery);
    btgal.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pickpic();
        }
    });

}

private void upload() {
    // Image location URL
    Log.e("path", "----------------" + picturePath);

    // Image
    Bitmap bm = BitmapFactory.decodeFile(picturePath);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
    byte[] ba = bao.toByteArray();
    ba1 =Base64.encodeToString(ba, Base64.DEFAULT);

    Log.e("base64", "-----" + ba1);

    // Upload image to server
    new uploadToServer().execute();

}

private void clickpic() {
    // Check Camera
    if (getApplicationContext().getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_CAMERA)) {
        // Open default camera
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        // start the image capture Intent
        startActivityForResult(intent, 100);

    } else {
        Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
    }
}

private void pickpic(){
    //Choose from the gallery
    // Create intent to Open Image applications like Gallery, Google Photos
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    // Start the Intent
    startActivityForResult(galleryIntent, RESULT_LOAD_IMG);


}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 100 && resultCode == RESULT_OK) {

        selectedImage = data.getData();
        photo = (Bitmap) data.getExtras().get("data");

        // Cursor to get image uri to display

        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        picturePath = cursor.getString(columnIndex);
        cursor.close();

        Bitmap photo = (Bitmap) data.getExtras().get("data");
        ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
        imageView.setImageBitmap(photo);
    }

    if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
            && null != data) {
        // Get the Image from data

        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        // Get the cursor
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        // Move to first row
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        picturePath = cursor.getString(columnIndex);
        cursor.close();
        ImageView imgView = (ImageView) findViewById(R.id.Imageprev);
        // Set the Image in ImageView after decoding the String
        imgView.setImageBitmap(BitmapFactory
                .decodeFile( picturePath));
    }

}

public class uploadToServer extends AsyncTask<Void, Void, String> {

    private ProgressDialog pd = new ProgressDialog(MainActivity.this);
    protected void onPreExecute() {
        super.onPreExecute();
        pd.setMessage("Wait image uploading!");
        pd.show();
    }

    @Override
    protected String doInBackground(Void... params) {

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("image", ba1));
        nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL);


            MultipartEntityBuilder mpEntity=MultipartEntityBuilder.create();
          mpEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

             File file = new File(picturePath);
              Log.d("EDIT USER PROFILE", "UPLOAD: file length = " + file.length());
              Log.d("EDIT USER PROFILE", "UPLOAD: file exist = " + file.exists());
              mpEntity.addPart("image", new FileBody(file));

                    HttpEntity entity = mpEntity.build();
                httppost.setEntity(entity);
                HttpResponse response = httpclient.execute(httppost);
                String st = EntityUtils.toString(response.getEntity());
                Log.v("log_tag", "In the try Loop" + st);



        } catch (Exception e) {
            Log.v("log_tag", "Error in http connection " + e.toString());
        }
        return "Success";

    }

    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        pd.hide();
        pd.dismiss();
     }
  }
 }
Valery Viktorovsky
  • 6,487
  • 3
  • 39
  • 47
CHENGJIE LIN
  • 21
  • 1
  • 2
  • BTW, i am testing it one a TI AM335x Starter kit. – CHENGJIE LIN Jul 09 '15 at 21:45
  • "App stopped"??? Crashed or show ANR? – JiTHiN Jul 10 '15 at 00:20
  • The name of my app is Cloud, and the error message is "Unfortunately, Cloud Stopped". – CHENGJIE LIN Jul 10 '15 at 03:08
  • Post your error log, the reason for the crash should be in there. – JiTHiN Jul 10 '15 at 16:32
  • The error log is like: 07-10 17:38:56.965 76-120/? E/audio_hw_primary﹕ cannot open pcm_out driver: cannot open device '/dev/snd/pcmC0D0p': No such file or directory 1211-1211/com.ascc.cloud E/WindowManager﹕ Activity com.ascc.cloud.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@410c74b8 that was originally added here android.view.WindowLeaked: Activity com.ascc.cloud.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@410c74b8 that was originally added here – CHENGJIE LIN Jul 10 '15 at 17:39

2 Answers2

1

After try lots of answer, I concluded below straight forward solution, Hope it will help some of you to integrate MultipartEntityBuilder in Gradle configuration in Android Studio. This is working Charm with Api Version 23.

Edit Module level buid.gradle file as follow:

android {
    ...
    packagingOptions {
         exclude 'META-INF/DEPENDENCIES'
         exclude 'META-INF/NOTICE'
         exclude 'META-INF/LICENSE'
         exclude 'META-INF/LICENSE.txt'
         exclude 'META-INF/NOTICE.txt'
    }
}

dependencies {
    ...
    compile "org.apache.httpcomponents:httpcore:4.4.1"
    compile "org.apache.httpcomponents:httpmime:4.3.6" 
}
Kalpesh
  • 1,767
  • 19
  • 29
0

In your app gradle, add these dependencies:

dependencies {

    compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5'
    compile (group: 'org.apache.httpcomponents' , name: 'httpmime' , version: '4.3.5') {
        exclude module: 'org.apache.httpcomponents:httpclient'
    }

}

Also, add following packaging options:

android {
    ...

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
    }
}
user5155835
  • 4,392
  • 4
  • 53
  • 97
  • compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1' i am using this for adding name value pair . so i can't add this particular dependencies for multi part. what should i do to add this dependencies – DKV Dec 14 '15 at 12:15