1

嗨,我从另一个 stackoverflow 问题中找到了以下代码片段,以打开相机和图库意图选择器组合。这是代码。

            Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT,null);
            galleryIntent.setType("image/*");
            galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);

            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
            cameraIntent.putExtra("Code", OPEN_CAMERA); <-- Not working


            Intent chooser = new Intent(Intent.ACTION_CHOOSER);
            chooser.putExtra(Intent.EXTRA_INTENT, galleryIntent);
            chooser.putExtra(Intent.EXTRA_TITLE, "Snap Option");
            chooser.putExtra("Code", OPEN_GALLERY);    <-- Not working

            Intent[] intentArray =  {cameraIntent}; 
            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
            startActivityForResult(chooser,1);

我想要做的是检查当我进入onActivityResult. 但正如代码中提到的,我试图通过putExtra参数来区分,并且onActivityResult我正在执行以下操作来获取代码。

int Code = intent.getExtras().getInt("Code");

但这给了我一个NullPointerException. 我该怎么做请帮忙?

4

1 回答 1

0

你必须使用一些东西来从中挑选图像..

警报框、对话框、自定义对话框等等。我只是指导您如何使用警报对话框。

final CharSequence[] items = { "Take Photo", "Choose from Library","Cancel" };
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {
                    //you can take photo from camera
                    /*Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivityForResult(intent, REQUEST_CAMERA);*/
                } else if (items[item].equals("Choose from Library")) {
                //you can pick photo from library/gallery
                 /*   Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);*/
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show(); 
于 2013-06-28T04:44:53.203 回答