'How i can get Uri from intent?

I did

@Override
public void onClick(View v) {
    switch (v.getId()){
        //если выбрали камеру - запускаем ее
        case R.id.b_camera:
            //uri = generateFileUri();
            if (uri == null) {
                Toast.makeText(getView().getContext(), getResources().getString(R.string.sdnot), Toast.LENGTH_LONG).show();
                return;
            }
            Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            //intentCamera.putExtra("return-data", true);
            startActivityForResult(intentCamera, PHOTO_INTENT_REQUEST_CODE);
        break;
    }
}

Method generateFileUri() is called in onCreateView(). Line intentCamera.putExtra("return-data", true); doesnot work for me (if use "return-data" as a key in onActivityResult at getParceble()).

@Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturned) {

    switch (requestCode) {

        //если результат пришел от камеры
        case PHOTO_INTENT_REQUEST_CODE:
            if (resultCode == getActivity().RESULT_OK) {
                Log.i("HHHHHHHHHHHH", "result ok");
                //извлекаем uri фотки из интента
                Uri selectedImage = imageReturned.getData();
                Log.i("HHHHHHHHHHHH", "getdata works!");
                //создаем интент для запуска новой активити
                Intent last_intent_photo = new Intent(getView().getContext(), ViewPhoto.class);
                //помещаем в интент этот uri
                last_intent_photo.putExtra("fotka",selectedImage);
                //стартуем новую активити
                startActivity(last_intent_photo);

            } else if (resultCode == getActivity().RESULT_CANCELED)
                Toast.makeText(getView().getContext(), "Capture cancelled", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(getView().getContext(), "Capture failed", Toast.LENGTH_LONG).show();
                break;
        default: super.onActivityResult(requestCode, resultCode, imageReturned);

    }
}

I see log "result ok". I think it meens camera did work well. But then i see: Failure delivering result ResultInfo{who=android:fragment:2, request=100, result=-1, data=null}. How it can be?!

Well, i tried Uri selectedImage = imageReturned.getExtras().getParcelable(); but i have not a key in my intent to put it into getParcelable(String key).

So, why result is ok, but data=null?



Solution 1:[1]

Option 1:

//Uri myUri = ...
intent.setData(myUri);

and

Uri uri = intent.getData();

Option 2:

According to documentation:

toString() - Returns the encoded string representation of this URI

//Uri myUri = ...
intent.putStringExtra("uri",myUri.toString());

and

String uriString = intent.getStringExtra("uri");
Uri uri = Uri.parse(uriString);

Solution 2:[2]

why do you need to get the uri from intert since you are passing it youself? just use the same uri as:

intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);

UPD to clarify:

when you're starting the cameta with option:

intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);

you are telling to the camera that the photo must be stored in this path. so, if the result OK you need to get that photo by this uri.

 if (resultCode == getActivity().RESULT_OK) {
    Log.i("HHHHHHHHHHHH", "result ok");

    // same as passed in intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    Uri selectedImage = uri; 

    Log.i("HHHHHHHHHHHH", "getdata works!");
    //??????? ?????? ??? ??????? ????? ????????
    Intent last_intent_photo = new Intent(getView().getContext(), ViewPhoto.class);
    //???????? ? ?????? ???? uri
    last_intent_photo.putExtra("fotka",selectedImage);
    //???????? ????? ????????
    startActivity(last_intent_photo);
} 

UPD 2

FragmentScaling.onActivityCreated:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (getActivity().getIntent().hasExtra("uri")) {
        uri = (Uri)getActivity().getIntent().getParcelableExtra("uri");
    }
}

Solution 3:[3]

MainActivity

    public class MainActivity extends AppCompatActivity {

    FragmentManager fragmentManager;
    PreferenceHelper preferenceHelper;

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

        PreferenceHelper.getInstance().init(getApplicationContext());
        preferenceHelper = PreferenceHelper.getInstance();

        fragmentManager = getFragmentManager();

        runSplash();

        setUI();
    }


    //????? ??? ???????? ??????????
    private void setUI(){
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null){
            toolbar.setTitleTextColor(getResources().getColor(R.color.white));
            setSupportActionBar(toolbar);
        }
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_list_white_18dp).setText(R.string.listtab));
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_camera_alt_white_18dp).setText(R.string.scalingtab));
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_web_asset_white_18dp).setText(R.string.parsingtab));
        tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_my_location_white_18dp).setText(R.string.maptab));

        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        TabAdapter tabAdapter = new TabAdapter(fragmentManager, 4);
        viewPager.setAdapter(tabAdapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
}

I can not even imagine where exactly to look for the error ...

//???????? ????????? ?? ??????? ??? ??????
@Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturned) {

    switch (requestCode) {

        //???? ????????? ?????? ?? ??????
        case PHOTO_INTENT_REQUEST_CODE:
            if (resultCode == getActivity().RESULT_OK && imageReturned != null) {
                Log.i("HHHHHHHHHHHH", "result ok"); // ?????????? ? ????
                //????????? uri ????? ?? ???????
                Uri selectedImage = uri;
                Log.i("HHHHHHHHHHHH", "getdata works!"); //? ???? ?? ??????????!
                //??????? ?????? ??? ??????? ????? ????????
                Intent last_intent_photo = new Intent(getView().getContext(), ViewPhoto.class);
                //???????? ? ?????? ???? uri
                last_intent_photo.putExtra("fotka", selectedImage);
                //???????? ????? ????????
                startActivity(last_intent_photo);

            } else if (resultCode == getActivity().RESULT_CANCELED)
                Toast.makeText(getView().getContext(), "Capture cancelled", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(getView().getContext(), "Capture failed", Toast.LENGTH_LONG).show();
                break;
        default: super.onActivityResult(requestCode, resultCode, imageReturned);

    }
}

Solution 4:[4]

recently onActivityResult has been deprecated so because of that

private val getIntent = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode == Activity.RESULT_OK) {
            if (it.data != null) {
                val imageUri = it.data!!.data as Uri
                val image = yourCustomMethod(imageUri)
            }
        }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3
Solution 4 Neil