3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

対策例:startActivityForResult(Intent,int) in Fragment has been deprecated

Last updated at Posted at 2021-06-23

背景

startActivityForResult(Intent,int) での画像選択コードが deprecated と言われるので、修正前後のコード例を残しておく。

コード

修正前

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private final static int RESULT_PICK_IMAGEFILE = 1000;

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

        if (requestCode == RESULT_PICK_IMAGEFILE && resultCode == RESULT_OK) {
            if (resultData != null) {
                Uri uri = resultData.getData();

                // Do something here.
            }
        }
    }

    private void onSelectImage() {

        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);

        startActivityForResult(intent, RESULT_PICK_IMAGEFILE); // deprecated!!
    }
}

修正後

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    ActivityResultLauncher<Intent> _launcherSelectSingleImage = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == RESULT_OK) {
                        Intent      resultData = result.getData();
                        if (resultData != null) {
                            Uri uri = resultData.getData();

														// Do something here.
                        }
                    }
                }
            });


    private void onSelectImage() {

        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
        Intent chooserIntent = Intent.createChooser(intent, "単一画像の選択");

        _launcherSelectSingleImage.launch(chooserIntent);
    }
}

参考リンク

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?