我想在非活动课上拍照。但是我得到错误:尝试在空对象引用上调用虚方法。这是我的代码:
MainAcvitity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Print myprint = new Print();
myprint.Picture();
}
Print.java
public class Print {
private static final String TAG = "Secret";
Context context;
public void Picture() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
((Activity) this.context).startActivityForResult(intent, 1);
Log.v(TAG, "I took a picture.");
}
}
我不知道出了什么问题。你能告诉我为什么会这样,我该如何解决?我不希望我的Print类成为Activity类。如果Print是Activity类,我知道如何拍照。 0.0
答案 0 :(得分:4)
因为您的上下文为null。你尚未初始化它。
如果您想创建一个类来打开相机,请尝试以下方法:
public class Print{
private static final String TAG = "Secret";
private Context context;
private File photoCaptured;
public Print(Context context) {
this.context = context;
}
public void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = System.currentTimeMillis() + "";
String fileName = "JPEG_" + timeStamp;
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
photoCaptured = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES),
fileName + ".jpg");
} else {
String dir = Environment.getExternalStorageDirectory() + File.separator + "myDirectory";
//create folder
File folder = new File(dir); //folder name
if (!folder.exists()) {
folder.mkdirs();
}
//create file
photoCaptured = new File(dir, fileName + ".jpg");
}
Uri temUri = Uri.fromFile(photoCaptured);
intent.putExtra(MediaStore.EXTRA_OUTPUT, temUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
if (intent.resolveActivity(context.getPackageManager()) != null) {
((AppCompatActivity) context).startActivityForResult(intent, REQUEST_TAKE_PHOTO);
}
}
}
然后在MainActivity
中,初始化Print
并使用它。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Print myprint = new Print(this);
myprint.openCamera();
}
对于您的问题,只需初始化您的Print
课程即可。 (仅适用于您的情况,但这不是最佳方法!!!)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Print myprint = new Print(this);
myprint.Picture()
}