发生了什么:
showCameraApp()
被调用。 currentPhotoPath
设置为/mnt/sdcard/20_08_22_06_33.jpg
(当前日期)。Intent
以startActivityForResult
开头)。onActivityResult()
中的应用程序并调用cameraManager.getPhoto()
。currentPhotoPath
中的cameraManager.getPhoto()
是null
! 问题(随意回答任何问题,不一定全部回答):
currentPhotoPath
尽管设置null
仍是currentPhotoPath
? Intent
存储在私有变量中,也许我可以使用intent.putExtra("some", "thing")
传递它?我尝试使用Intent data
,但后来null
为Bitmap
。 volatile
(不保存到冗余文件)?我的盲目猜测是,这可能是多线程的,所以我已将currentPhotoPath
添加到MainActivity
,但它没有帮助。
public class MainActivity extends Activity implements OnClickListener
{
private CameraManager cameraManager;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cameraManager = new CameraManager(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CameraManager.REQUEST_CODE && resultCode == RESULT_OK)
{
Bitmap bitmap = cameraManager.getPhoto(); // HERE bitmap is null!
}
}
}
上课:
CameraManager
public class CameraManager
{
public final static int REQUEST_CODE = 666;
private /*volatile*/ String currentPhotoPath; // THIS VARIABLE BEHAVES STRANGE
private final Activity activity;
public CameraManager(Activity activity)
{
this.activity = activity;
}
public void showCameraApp()
{
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
currentPhotoPath = createNewPhotoPath(); // HERE currentPhotoPath is set
final File file = new File(currentPhotoPath);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
activity.startActivityForResult(intent, REQUEST_CODE);
}
private String createNewPhotoPath()
{
final String date = new SimpleDateFormat("dd_MM_HH_mm_ss", Locale.UK).format(new Date());
return Environment.getExternalStorageDirectory() + "/" + date + ".jpg";
}
public Bitmap getPhoto()
{
return BitmapFactory.decodeFile(currentPhotoPath); // HERE currentPhotoPath is null!
}
}
上课:
{{1}}
答案 0 :(得分:2)
我想,当你回来时会创建一个MainActivity
的新实例。因此,您还要分配一个没有字段集的CameraManager
的新实例。
请查看文档中的Saving Activity State。
答案 1 :(得分:0)
尝试从意图中获取数据:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}