Home Ask Login Register

Developers Planet

Your answer is one click away!

Kenny Jay Jaudian February 2016

My app force closes after selecting an image from gallery

I am trying to make an upload function in my app, but my app force closes after selecting an image on the gallery. this is my code


public class AddCategory extends AppCompatActivity implements View.OnClickListener {

private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editTextName;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 1;
private String UPLOAD_URL ="http://knyjayjay.16mb.com/products/upload.php";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
protected void onCreate(Bundle savedInstanceState) {
    buttonUpload = (Button) findViewById(R.id.btn_addCat);
    buttonChoose = (Button) findViewById(R.id.chooseimgbtn);
    buttonChoose = (Button) findViewById(R.id.chooseimgbtn);
    buttonUpload = (Button) findViewById(R.id.btn_addCat);
    editTextName = (EditText) findViewById(R.id.input_name);
    imageView  = (ImageView) findViewById(R.id.imageView);
public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
private void uploadImage(){
    //Showing the progress dialog
    final ProgressDialog loading = ProgressDialog.show(this,"Uploading","Please wait...",false,false);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
            new Response.Listener<String>() {
                public void onResponse(String s) {
                    //Disimissing the progress dialog
                    //Showing t        


Cochi February 2016

The image URI can change according to the source, this method should work :

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            try {
                Uri filePathUri = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(
                                    filePathUri, filePathColumn, null, null, null);

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = cursor.getString(columnIndex);

                bitmap = BitmapFactory.decodeFile(filePath);
            } catch(NullPointerException e) {

Post Status

Asked in February 2016
Viewed 2,809 times
Voted 9
Answered 1 times


Leave an answer

Quote of the day: live life