1

I tried to get image from gallery and capture from camera and display image in my imageView using fragment but the onActivityResult() does not response. Below is my code for capturing image from camera or gallery.

final CharSequence[] items = { "Take Photo", "Choose from Library",
            "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                final Intent intent = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
                startActivityForResult(intent, CAPTURE_IMAGE);
            } else if (items[item].equals("Choose from Library")) {

                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, ""),
                        PICK_IMAGE);
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    System.out.println("OnActivityResult Call");
    if (resultCode != Activity.RESULT_CANCELED) {
        if (requestCode == PICK_IMAGE) {
            imagePath = getAbsolutePath(data.getData());
            myImageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageLoader.displayImage("file://" + imagePath, ivUpload,
                    options);
        } else if (requestCode == CAPTURE_IMAGE) {
            imagePath = getImagePath();
            System.out.println("IMAGE PATH===" + imagePath);
            myImageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageLoader.displayImage("file://" + imagePath, ivUpload,
                    options);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}

private String getAbsolutePath(Uri uri) {
    String[] projection = { MediaColumns.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = getActivity().managedQuery(uri, projection, null, null,
            null);
    if (cursor != null) {
        int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } else
        return null;
}

private Uri setImageUri() {
    File file = new File(Environment.getExternalStorageDirectory()
            + "/DCIM/", "image" + new Date(CAPTURE_IMAGE).getTime()
            + ".png");
    Uri imgUri = Uri.fromFile(file);
    this.imagePath = file.getAbsolutePath();
    return imgUri;
}

private String getImagePath() {
    return imagePath;
}

please give me any solution for that fragment. i also try with in activity. it is work but in fragment does not upload image from gallery.

Elesh Baraiya
  • 231
  • 1
  • 6
  • 16

4 Answers4

4

That fragment does the job

public class ClientFormFragment extends Fragment {
public static final String TAG = "Test";

private ScrollView mScrollView;
private LinearLayout mFormView;

private static int RESULT_LOAD_IMAGE = 1;
Uri myPicture = null;
Button buttonLoadImage;


private static int sId = 0;

private static int id() {
    return sId++;
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    Log.d(TAG, "onAttach(): activity = " + activity);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate(): savedInstanceState = " + savedInstanceState);
    setRetainInstance(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    Log.d(TAG, "onCreateView(): container = " + container
            + "savedInstanceState = " + savedInstanceState);

    if (mScrollView == null) {
        // normally inflate the view hierarchy
        mScrollView = (ScrollView) inflater.inflate(R.layout.bmr__fragment_client_form,container, false);
        mFormView = (LinearLayout) mScrollView.findViewById(R.id.form);

        buttonLoadImage = (Button) mScrollView.findViewById(R.id.select);

        buttonLoadImage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });


    } else {

        ViewGroup parent = (ViewGroup) mScrollView.getParent();
        parent.removeView(mScrollView);
    }
    return mScrollView;
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE  && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getActivity().getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

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

        ImageView imageView = (ImageView) mFormView.findViewById(R.id.imageView);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

    }


}


@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Log.d(TAG, "onActivityCreated(): savedInstanceState = "
            + savedInstanceState);

}

@Override
public void onDestroyView() {
    super.onDestroyView();
    Log.d(TAG, "onDestroyView()");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy()");
}

@Override
public void onDetach() {
    super.onDetach();
    Log.d(TAG, "onDetach()");
}



public void onLoadFinished(Loader<Void> id, Void result) {
    Log.d(TAG, "onLoadFinished(): id=" + id);
}

public void onLoaderReset(Loader<Void> loader) {
    Log.d(TAG, "onLoaderReset(): id=" + loader.getId());
}



}

With that XML

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroll_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true"
    android:isScrollContainer="false">

    <LinearLayout
        android:id="@+id/form"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:weightSum="1">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="10px"
                android:paddingTop="20px"
                android:text="Name" />

            <EditText
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.50"
                android:paddingTop="20px" />


        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="City"
                android:paddingTop="20px"
                android:paddingLeft="10px" />

            <EditText
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.50"
                android:paddingTop="20px" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Zip code"
                android:paddingTop="20px"
                android:paddingLeft="10px" />

            <EditText
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.50"
                android:paddingTop="20px"
                android:inputType="number" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Address"
                android:paddingTop="20px"
                android:paddingLeft="10px" />

            <EditText
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0.50"
                android:paddingTop="20px" />

        </LinearLayout>


        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Notes"
                android:paddingTop="20px"
                android:paddingLeft="10px" />

            <EditText
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:inputType="textLongMessage"
                android:layout_weight="0.50"
                android:paddingTop="20px" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Status"
                android:paddingTop="20px"
                android:paddingLeft="10px" />

            <RadioGroup
                android:id="@+id/radioStatus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <RadioButton
                    android:id="@+id/radioAccepted"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Accepted"
                    android:checked="true" />

                <RadioButton
                    android:id="@+id/radioWaiting"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Waiting" />

                <RadioButton
                    android:id="@+id/radioRefused"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Refused" />

            </RadioGroup>

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Pictures"
                android:paddingTop="20px"
                android:paddingLeft="10px" />

            <Button
                android:id="@+id/select"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingTop="20px"
                android:text="Select" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingTop="20px">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/imageView"
                />

        </LinearLayout>


        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:paddingTop="20px"
            android:text="Create" />
    </LinearLayout>
</ScrollView>
tomzi
  • 1,215
  • 1
  • 12
  • 23
3

If you have Image path, you can directly display image from image path..

You can write like this...

 imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

BitmapFactory.decodeFile() method allows you to decode image from file path. so you can set decoded image directly to the ImageView by setImageBitmap() method.

Edit :

Here I am adding sample code for picking intent..
You can take reference and see whats the problem there..

To Call Image Intent

Intent i = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, RESULT_LOAD_IMAGE);

Activity Result

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


       if (data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = context.getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);

            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            img_user.setImageBitmap(BitmapFactory.decodeFile(picturePath));
            btn_set.setEnabled(true);
            cursor.close();
        } else {
            Toast.makeText(getActivity(), "Try Again!!", Toast.LENGTH_SHORT)
                    .show();
        }

}

This may help you..

Pragnesh Ghoda シ
  • 8,318
  • 3
  • 25
  • 40
  • sorry friends, i also try your answer but onActivityResult() does not call. i don't know what problem. – Elesh Baraiya Sep 10 '14 at 07:10
  • @EleshBaraiya :: see [onActivityResult not being called in Fragment](http://stackoverflow.com/questions/6147884/onactivityresult-not-being-called-in-fragment) may help in solving issue – ρяσѕρєя K Sep 10 '14 at 07:13
  • @Prags thanks your response but my problem is not solve. can you answer for what reason behind onActivityResult() does not called in fragment? – Elesh Baraiya Sep 10 '14 at 07:17
  • imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath)); is also works in fragments.. – Pragnesh Ghoda シ Sep 10 '14 at 07:20
3

u can set image from gallery

private static int RESULT_LOAD_IMAGE = 1;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
            buttonLoadImage.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    Intent i = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                    startActivityForResult(i, RESULT_LOAD_IMAGE);
                }
            });
        }


        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

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

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

                ImageView imageView = (ImageView) findViewById(R.id.imgView);
                imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

            }


        }
Galmani
  • 71
  • 7
0

Override onActivityResult in activity.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

        fragment.onActivityResult(requestCode, resultCode, data);

}
navneet sharma
  • 680
  • 4
  • 7
  • sorry friend, i am using Fragment not Activity. – Elesh Baraiya Sep 10 '14 at 08:33
  • yes...but in main activity where you use add fragment use this code – navneet sharma Sep 10 '14 at 08:44
  • i don't getting idea. because i am using below code. FragmentTransaction fragmentTransaction = getSupportFragmentManager() .beginTransaction(); NewNoteFragment fragment = new NewNoteFragment(); fragmentTransaction.replace(R.id.flMain, fragment); fragmentTransaction.commit(); – Elesh Baraiya Sep 10 '14 at 08:50