我如何从意图中获得Uri?

时间:2016-05-11 11:24:47

标签: android android-intent android-camera

我做了

@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;
    }
}

在onCreateView()中调用方法generateFileUri()。 Line intentCamera.putExtra(“return-data”,true);对我不起作用(如果在getParceble()中使用“return-data”作为onActivityResult中的键)。

@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);

    }
}

我看到日志“结果正常”。我认为相机确实很好用。 但后来我看到:失败交付结果ResultInfo {who = android:fragment:2,request = 100,result = -1,data = null}。它怎么样?!

好吧,我试过Uri selectedImage = imageReturned.getExtras()。getParcelable();但是我没有关键意图将它放入getParcelable(String key)。

那么,为什么结果没问题,但是data = null?

4 个答案:

答案 0 :(得分:3)

选项1:

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

Uri uri = intent.getData();

选项2:

根据文件:

  

toString() - 返回此URI

的编码字符串表示形式
//Uri myUri = ...
intent.putStringExtra("uri",myUri.toString());

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

答案 1 :(得分:2)

为什么你需要从uri获得intert,因为你自己传递了它?只需使用相同的uri

intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);

UPD澄清

当你用选项启动cameta时:

intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);

您告诉相机必须将照片存储在此路径中。所以,如果结果确定你需要通过这个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");
    }
}

答案 2 :(得分:0)

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) {

            }
        });
    }
}

我甚至无法想象究竟在哪里寻找错误......

//получаем результат из галереи или камеры
@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);

    }
}

答案 3 :(得分:0)

最近 onActivityResult 已被弃用,因此

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)
            }
        }