1

I wrote a code that the user can take a picture or choose from his libary. I used intent to open the gallery/camera, it returns the bitmap or the path of the file from the gallery. The data that i received i try to save it on interface but for some reason it always crash because its get null.

I dont understand how the interface gets null if it actually get the bitmap/file path.

CODE

     public class ChangeProfileImgDialog extends DialogFragment {

private static final String TAG = "ChangePhotoDialog";

public static final int  CAMERA_REQUEST_CODE = 1;//random number
public static final int PICKFILE_REQUEST_CODE = 0;//random number

public ChangeProfileImgDialog() {
    // Required empty public constructor
}

public interface OnPhotoReceivedListener{
    public void getImagePath(Uri imagePath);
    public void getImageBitmap(Bitmap bitmap);
}

OnPhotoReceivedListener mOnPhotoReceived;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_change_profile_img_dialog, container, false);

    //Initialize the textview for choosing an image from memory
    TextView selectPhoto = (TextView) v.findViewById(R.id.dialogChoosePhoto);
    selectPhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: accessing phones memory.");
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(intent, PICKFILE_REQUEST_CODE);
        }
    });


    //Initialize the textview for choosing an image from memory
    TextView takePhoto = (TextView) v.findViewById(R.id.dialogOpenCamera);
    takePhoto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: starting camera");
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
        }
    });

    return v;

}

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

    /*
    Results when selecting new image from phone memory
     */
    if(requestCode == PICKFILE_REQUEST_CODE && resultCode == Activity.RESULT_OK){
        Uri selectedImageUri = data.getData();
        Log.d(TAG, "onActivityResult: image: " + selectedImageUri);

        //send the uri and fragment to the interface
        mOnPhotoReceived.getImagePath(selectedImageUri);
        getDialog().dismiss();

    }

    else if(requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK){
        Log.d(TAG, "onActivityResult: done taking a photo.");

        Bitmap bitmap;
        bitmap = (Bitmap) data.getExtras().get("data");
        //send the bitmap and fragment to the interface
        mOnPhotoReceived.getImageBitmap(bitmap);
        getDialog().dismiss();
    }
}

@Override
public void onAttach(Context context) {
    try{
        mOnPhotoReceived = (OnPhotoReceivedListener) getActivity();
    }catch (ClassCastException e){
        Log.e(TAG, "onAttach: ClassCastException", e.getCause() );
    }
    super.onAttach(context);
   }

 }

The device that i run the app is Xiaomi A1 - i dont know if it is related.

EDIT

I have resolve the problem by implement the interface in "MainActivity" and call the func of the interface and pass the data and it work!

    //transfer the imagepath to MyAccountFragment
@Override
public void getImagePath(Uri imagePath) {
    Log.d(TAG,imagePath.toString());
    MyAccountFragment fragment = new MyAccountFragment();
    fragment.getImagePath(imagePath);
}

//transfer the bitmap to MyAccountFragment
@Override
public void getImageBitmap(Bitmap bitmap) {
    Log.d(TAG,bitmap.toString());
    MyAccountFragment fragment = new MyAccountFragment();
    fragment.getImageBitmap(bitmap);
}

Thats all i needed to do

E.Bolandian
  • 553
  • 10
  • 35

1 Answers1

1

Your MainActivity(Activity on which all fragments rely) need to implement the interface which you need use in the Fragment

Now the problem is that how you will transfer data from Activity to Fragment for which, you need to use the findFragmentById method of the Fragment, have a look on the example on which i have transferred the data from Activity to Fragment

public class MainActivity extends AppCompatActivity implements OnPhotoReceivedListener {


    @Override
    public void getImagePath(String name) {

        YOUR_FRAGMENT fragment = (YOUR_FRAGMENT) getFragmentManager().findFragmentById(R.id.fragment_container);
        fragment.setDataForInterface(name);  //// THESE METHOD , YOU NEED TO CREATE ON THE FRAGMENT

    }
}

Inside your onCreateView , you need to initialize the OnPhotoReceivedListener interface like below

 OnPhotoReceivedListener mOnPhotoReceived;

 @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
          /**
           * This is the main error which u are doing
           */

        try {
            mOnPhotoReceived = (OnPhotoReceivedListener ) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement MyInterface ");
        }
    }

You need to create the method which will take the data from your parent Activity to Fragment

   public void setDataForInterface(String yourData) {
           /**
            * THIS IS YOUR DATA WHICH IS COME FROM THE PARENT ACTIVITY
            */
    }
Ravindra Kushwaha
  • 7,846
  • 14
  • 53
  • 103
  • I added that line of code, but it crash my app. Actually this line of code i use in "onAttach" – E.Bolandian Sep 10 '18 at 11:39
  • @E.Bolandian Please check my updated solution i have added the code inside the _onAttach()_ , please check the solution – Ravindra Kushwaha Sep 10 '18 at 11:42
  • @Override public void onAttach(Context context) { super.onAttach(context); try{ mOnPhotoReceived = (OnPhotoReceivedListener) getActivity(); }catch (ClassCastException e){ Log.e(TAG, "onAttach: ClassCastException", e.getCause() ); } } Still crash – E.Bolandian Sep 10 '18 at 11:54
  • @E.Bolandian have a look on the solution...My one question why u need the interace for saving the image path/bitmap? – Ravindra Kushwaha Sep 10 '18 at 12:35
  • I think i have found the problem but i dont know how to resolve it. The app crash beacuse the mOnPhotoReceived is null - i have no idea ,if i initialize it in "onAttach" – E.Bolandian Sep 10 '18 at 12:46
  • @E.Bolandian CAn u please tell me about the use of the interface for saving the data ?We can also use the setArgument OR getArugment() for fragements – Ravindra Kushwaha Sep 10 '18 at 13:03
  • I have fragment that open an DialogFragment. in the DialogFragment i pick/take a photo and then i pass the data back to the fragment with the interface – E.Bolandian Sep 10 '18 at 13:07
  • @E.Bolandian Your solution is here [Click](https://stackoverflow.com/a/19677039/3946958)..Please have look on it and let me know – Ravindra Kushwaha Sep 10 '18 at 13:30
  • Thats can be a god solution but i have found the problem, but yet i dont know how to fix it. The problem is that in the "onAttached" it gives me "ClassCastException". And thats why it skips the "try" and jump to "catch". Have any idea why? – E.Bolandian Sep 10 '18 at 13:43
  • @E.Bolandian Finally got some solution for u ......... If you need to add the **interface** inside the **Fragment** than Your **_parent activity_** (Activity on which fragment exits) need to implement that **Fragment**..Than your problem will resolve – Ravindra Kushwaha Sep 10 '18 at 13:51
  • Thank you, I have found the problem. I needed to implement the interface in the MainActivity. now its works fine! the only thing is how do i transfer the data that i have received to the fragment? – E.Bolandian Sep 10 '18 at 14:25