0
我正在創建一個應用程序,它從相機捕獲圖像並將圖像保存在文件中。在onActivityResult()方法我收到空對象引用錯誤。 我的片段類是在這裏:在套件中獲取null對象引用getExtras()方法
public class HomeFragment extends Fragment {
private static final int REQUEST_IMAGE_CAPTURE = 1;
private static final String JPEG_FILE_PREFIX = "IBR_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
File photoFile = null;
ImageButton camera_button;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
camera_button = (ImageButton) rootView.findViewById(R.id.camera);
camera_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i("File error", "File");
}
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri fileUri = Uri.fromFile(photoFile);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
fileUri);
Toast.makeText(getActivity(), photoFile.toString(), Toast.LENGTH_SHORT).show();
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
});
return rootView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
camera_button.setImageBitmap(imageBitmap);
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, storageDir);
return imageF;
}
}
其實我得到的錯誤在這行捆綁額外= data.getExtras(); 任何建議如何解決這個問題?
任何提示我該怎麼做? –
實際上它應該保存在從'createImageFile()'返回的路徑中,您可以將它複製到自己的位置,以獲取其InputStream使用以下代碼:'InputStream inputStream = context.getContentResolver()。openInputStream(fileUri) ;' – marcinj
其實我已經解決了使用Uri的問題。無論如何感謝您的回答。 –